models.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  1. """
  2. Helper functions for creating Form classes from Django models
  3. and database field objects.
  4. """
  5. from itertools import chain
  6. from django.core.exceptions import (
  7. NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError,
  8. )
  9. from django.forms.fields import ChoiceField, Field
  10. from django.forms.forms import BaseForm, DeclarativeFieldsMetaclass
  11. from django.forms.formsets import BaseFormSet, formset_factory
  12. from django.forms.utils import ErrorList
  13. from django.forms.widgets import (
  14. HiddenInput, MultipleHiddenInput, SelectMultiple,
  15. )
  16. from django.utils.text import capfirst, get_text_list
  17. from django.utils.translation import gettext, gettext_lazy as _
  18. __all__ = (
  19. 'ModelForm', 'BaseModelForm', 'model_to_dict', 'fields_for_model',
  20. 'ModelChoiceField', 'ModelMultipleChoiceField', 'ALL_FIELDS',
  21. 'BaseModelFormSet', 'modelformset_factory', 'BaseInlineFormSet',
  22. 'inlineformset_factory', 'modelform_factory',
  23. )
  24. ALL_FIELDS = '__all__'
  25. def construct_instance(form, instance, fields=None, exclude=None):
  26. """
  27. Construct and return a model instance from the bound ``form``'s
  28. ``cleaned_data``, but do not save the returned instance to the database.
  29. """
  30. from django.db import models
  31. opts = instance._meta
  32. cleaned_data = form.cleaned_data
  33. file_field_list = []
  34. for f in opts.fields:
  35. if not f.editable or isinstance(f, models.AutoField) \
  36. or f.name not in cleaned_data:
  37. continue
  38. if fields is not None and f.name not in fields:
  39. continue
  40. if exclude and f.name in exclude:
  41. continue
  42. # Leave defaults for fields that aren't in POST data, except for
  43. # checkbox inputs because they don't appear in POST data if not checked.
  44. if (
  45. f.has_default() and
  46. form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name)) and
  47. cleaned_data.get(f.name) in form[f.name].field.empty_values
  48. ):
  49. continue
  50. # Defer saving file-type fields until after the other fields, so a
  51. # callable upload_to can use the values from other fields.
  52. if isinstance(f, models.FileField):
  53. file_field_list.append(f)
  54. else:
  55. f.save_form_data(instance, cleaned_data[f.name])
  56. for f in file_field_list:
  57. f.save_form_data(instance, cleaned_data[f.name])
  58. return instance
  59. # ModelForms #################################################################
  60. def model_to_dict(instance, fields=None, exclude=None):
  61. """
  62. Return a dict containing the data in ``instance`` suitable for passing as
  63. a Form's ``initial`` keyword argument.
  64. ``fields`` is an optional list of field names. If provided, return only the
  65. named.
  66. ``exclude`` is an optional list of field names. If provided, exclude the
  67. named from the returned dict, even if they are listed in the ``fields``
  68. argument.
  69. """
  70. opts = instance._meta
  71. data = {}
  72. for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
  73. if not getattr(f, 'editable', False):
  74. continue
  75. if fields is not None and f.name not in fields:
  76. continue
  77. if exclude and f.name in exclude:
  78. continue
  79. data[f.name] = f.value_from_object(instance)
  80. return data
  81. def apply_limit_choices_to_to_formfield(formfield):
  82. """Apply limit_choices_to to the formfield's queryset if needed."""
  83. if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_to'):
  84. limit_choices_to = formfield.get_limit_choices_to()
  85. if limit_choices_to is not None:
  86. formfield.queryset = formfield.queryset.complex_filter(limit_choices_to)
  87. def fields_for_model(model, fields=None, exclude=None, widgets=None,
  88. formfield_callback=None, localized_fields=None,
  89. labels=None, help_texts=None, error_messages=None,
  90. field_classes=None, *, apply_limit_choices_to=True):
  91. """
  92. Return a dictionary containing form fields for the given model.
  93. ``fields`` is an optional list of field names. If provided, return only the
  94. named fields.
  95. ``exclude`` is an optional list of field names. If provided, exclude the
  96. named fields from the returned fields, even if they are listed in the
  97. ``fields`` argument.
  98. ``widgets`` is a dictionary of model field names mapped to a widget.
  99. ``formfield_callback`` is a callable that takes a model field and returns
  100. a form field.
  101. ``localized_fields`` is a list of names of fields which should be localized.
  102. ``labels`` is a dictionary of model field names mapped to a label.
  103. ``help_texts`` is a dictionary of model field names mapped to a help text.
  104. ``error_messages`` is a dictionary of model field names mapped to a
  105. dictionary of error messages.
  106. ``field_classes`` is a dictionary of model field names mapped to a form
  107. field class.
  108. ``apply_limit_choices_to`` is a boolean indicating if limit_choices_to
  109. should be applied to a field's queryset.
  110. """
  111. field_dict = {}
  112. ignored = []
  113. opts = model._meta
  114. # Avoid circular import
  115. from django.db.models.fields import Field as ModelField
  116. sortable_private_fields = [f for f in opts.private_fields if isinstance(f, ModelField)]
  117. for f in sorted(chain(opts.concrete_fields, sortable_private_fields, opts.many_to_many)):
  118. if not getattr(f, 'editable', False):
  119. if (fields is not None and f.name in fields and
  120. (exclude is None or f.name not in exclude)):
  121. raise FieldError(
  122. "'%s' cannot be specified for %s model form as it is a non-editable field" % (
  123. f.name, model.__name__)
  124. )
  125. continue
  126. if fields is not None and f.name not in fields:
  127. continue
  128. if exclude and f.name in exclude:
  129. continue
  130. kwargs = {}
  131. if widgets and f.name in widgets:
  132. kwargs['widget'] = widgets[f.name]
  133. if localized_fields == ALL_FIELDS or (localized_fields and f.name in localized_fields):
  134. kwargs['localize'] = True
  135. if labels and f.name in labels:
  136. kwargs['label'] = labels[f.name]
  137. if help_texts and f.name in help_texts:
  138. kwargs['help_text'] = help_texts[f.name]
  139. if error_messages and f.name in error_messages:
  140. kwargs['error_messages'] = error_messages[f.name]
  141. if field_classes and f.name in field_classes:
  142. kwargs['form_class'] = field_classes[f.name]
  143. if formfield_callback is None:
  144. formfield = f.formfield(**kwargs)
  145. elif not callable(formfield_callback):
  146. raise TypeError('formfield_callback must be a function or callable')
  147. else:
  148. formfield = formfield_callback(f, **kwargs)
  149. if formfield:
  150. if apply_limit_choices_to:
  151. apply_limit_choices_to_to_formfield(formfield)
  152. field_dict[f.name] = formfield
  153. else:
  154. ignored.append(f.name)
  155. if fields:
  156. field_dict = {
  157. f: field_dict.get(f) for f in fields
  158. if (not exclude or f not in exclude) and f not in ignored
  159. }
  160. return field_dict
  161. class ModelFormOptions:
  162. def __init__(self, options=None):
  163. self.model = getattr(options, 'model', None)
  164. self.fields = getattr(options, 'fields', None)
  165. self.exclude = getattr(options, 'exclude', None)
  166. self.widgets = getattr(options, 'widgets', None)
  167. self.localized_fields = getattr(options, 'localized_fields', None)
  168. self.labels = getattr(options, 'labels', None)
  169. self.help_texts = getattr(options, 'help_texts', None)
  170. self.error_messages = getattr(options, 'error_messages', None)
  171. self.field_classes = getattr(options, 'field_classes', None)
  172. class ModelFormMetaclass(DeclarativeFieldsMetaclass):
  173. def __new__(mcs, name, bases, attrs):
  174. base_formfield_callback = None
  175. for b in bases:
  176. if hasattr(b, 'Meta') and hasattr(b.Meta, 'formfield_callback'):
  177. base_formfield_callback = b.Meta.formfield_callback
  178. break
  179. formfield_callback = attrs.pop('formfield_callback', base_formfield_callback)
  180. new_class = super(ModelFormMetaclass, mcs).__new__(mcs, name, bases, attrs)
  181. if bases == (BaseModelForm,):
  182. return new_class
  183. opts = new_class._meta = ModelFormOptions(getattr(new_class, 'Meta', None))
  184. # We check if a string was passed to `fields` or `exclude`,
  185. # which is likely to be a mistake where the user typed ('foo') instead
  186. # of ('foo',)
  187. for opt in ['fields', 'exclude', 'localized_fields']:
  188. value = getattr(opts, opt)
  189. if isinstance(value, str) and value != ALL_FIELDS:
  190. msg = ("%(model)s.Meta.%(opt)s cannot be a string. "
  191. "Did you mean to type: ('%(value)s',)?" % {
  192. 'model': new_class.__name__,
  193. 'opt': opt,
  194. 'value': value,
  195. })
  196. raise TypeError(msg)
  197. if opts.model:
  198. # If a model is defined, extract form fields from it.
  199. if opts.fields is None and opts.exclude is None:
  200. raise ImproperlyConfigured(
  201. "Creating a ModelForm without either the 'fields' attribute "
  202. "or the 'exclude' attribute is prohibited; form %s "
  203. "needs updating." % name
  204. )
  205. if opts.fields == ALL_FIELDS:
  206. # Sentinel for fields_for_model to indicate "get the list of
  207. # fields from the model"
  208. opts.fields = None
  209. fields = fields_for_model(
  210. opts.model, opts.fields, opts.exclude, opts.widgets,
  211. formfield_callback, opts.localized_fields, opts.labels,
  212. opts.help_texts, opts.error_messages, opts.field_classes,
  213. # limit_choices_to will be applied during ModelForm.__init__().
  214. apply_limit_choices_to=False,
  215. )
  216. # make sure opts.fields doesn't specify an invalid field
  217. none_model_fields = {k for k, v in fields.items() if not v}
  218. missing_fields = none_model_fields.difference(new_class.declared_fields)
  219. if missing_fields:
  220. message = 'Unknown field(s) (%s) specified for %s'
  221. message = message % (', '.join(missing_fields),
  222. opts.model.__name__)
  223. raise FieldError(message)
  224. # Override default model fields with any custom declared ones
  225. # (plus, include all the other declared fields).
  226. fields.update(new_class.declared_fields)
  227. else:
  228. fields = new_class.declared_fields
  229. new_class.base_fields = fields
  230. return new_class
  231. class BaseModelForm(BaseForm):
  232. def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
  233. initial=None, error_class=ErrorList, label_suffix=None,
  234. empty_permitted=False, instance=None, use_required_attribute=None,
  235. renderer=None):
  236. opts = self._meta
  237. if opts.model is None:
  238. raise ValueError('ModelForm has no model class specified.')
  239. if instance is None:
  240. # if we didn't get an instance, instantiate a new one
  241. self.instance = opts.model()
  242. object_data = {}
  243. else:
  244. self.instance = instance
  245. object_data = model_to_dict(instance, opts.fields, opts.exclude)
  246. # if initial was provided, it should override the values from instance
  247. if initial is not None:
  248. object_data.update(initial)
  249. # self._validate_unique will be set to True by BaseModelForm.clean().
  250. # It is False by default so overriding self.clean() and failing to call
  251. # super will stop validate_unique from being called.
  252. self._validate_unique = False
  253. super().__init__(
  254. data, files, auto_id, prefix, object_data, error_class,
  255. label_suffix, empty_permitted, use_required_attribute=use_required_attribute,
  256. renderer=renderer,
  257. )
  258. for formfield in self.fields.values():
  259. apply_limit_choices_to_to_formfield(formfield)
  260. def _get_validation_exclusions(self):
  261. """
  262. For backwards-compatibility, exclude several types of fields from model
  263. validation. See tickets #12507, #12521, #12553.
  264. """
  265. exclude = []
  266. # Build up a list of fields that should be excluded from model field
  267. # validation and unique checks.
  268. for f in self.instance._meta.fields:
  269. field = f.name
  270. # Exclude fields that aren't on the form. The developer may be
  271. # adding these values to the model after form validation.
  272. if field not in self.fields:
  273. exclude.append(f.name)
  274. # Don't perform model validation on fields that were defined
  275. # manually on the form and excluded via the ModelForm's Meta
  276. # class. See #12901.
  277. elif self._meta.fields and field not in self._meta.fields:
  278. exclude.append(f.name)
  279. elif self._meta.exclude and field in self._meta.exclude:
  280. exclude.append(f.name)
  281. # Exclude fields that failed form validation. There's no need for
  282. # the model fields to validate them as well.
  283. elif field in self._errors:
  284. exclude.append(f.name)
  285. # Exclude empty fields that are not required by the form, if the
  286. # underlying model field is required. This keeps the model field
  287. # from raising a required error. Note: don't exclude the field from
  288. # validation if the model field allows blanks. If it does, the blank
  289. # value may be included in a unique check, so cannot be excluded
  290. # from validation.
  291. else:
  292. form_field = self.fields[field]
  293. field_value = self.cleaned_data.get(field)
  294. if not f.blank and not form_field.required and field_value in form_field.empty_values:
  295. exclude.append(f.name)
  296. return exclude
  297. def clean(self):
  298. self._validate_unique = True
  299. return self.cleaned_data
  300. def _update_errors(self, errors):
  301. # Override any validation error messages defined at the model level
  302. # with those defined at the form level.
  303. opts = self._meta
  304. # Allow the model generated by construct_instance() to raise
  305. # ValidationError and have them handled in the same way as others.
  306. if hasattr(errors, 'error_dict'):
  307. error_dict = errors.error_dict
  308. else:
  309. error_dict = {NON_FIELD_ERRORS: errors}
  310. for field, messages in error_dict.items():
  311. if (field == NON_FIELD_ERRORS and opts.error_messages and
  312. NON_FIELD_ERRORS in opts.error_messages):
  313. error_messages = opts.error_messages[NON_FIELD_ERRORS]
  314. elif field in self.fields:
  315. error_messages = self.fields[field].error_messages
  316. else:
  317. continue
  318. for message in messages:
  319. if (isinstance(message, ValidationError) and
  320. message.code in error_messages):
  321. message.message = error_messages[message.code]
  322. self.add_error(None, errors)
  323. def _post_clean(self):
  324. opts = self._meta
  325. exclude = self._get_validation_exclusions()
  326. # Foreign Keys being used to represent inline relationships
  327. # are excluded from basic field value validation. This is for two
  328. # reasons: firstly, the value may not be supplied (#12507; the
  329. # case of providing new values to the admin); secondly the
  330. # object being referred to may not yet fully exist (#12749).
  331. # However, these fields *must* be included in uniqueness checks,
  332. # so this can't be part of _get_validation_exclusions().
  333. for name, field in self.fields.items():
  334. if isinstance(field, InlineForeignKeyField):
  335. exclude.append(name)
  336. try:
  337. self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
  338. except ValidationError as e:
  339. self._update_errors(e)
  340. try:
  341. self.instance.full_clean(exclude=exclude, validate_unique=False)
  342. except ValidationError as e:
  343. self._update_errors(e)
  344. # Validate uniqueness if needed.
  345. if self._validate_unique:
  346. self.validate_unique()
  347. def validate_unique(self):
  348. """
  349. Call the instance's validate_unique() method and update the form's
  350. validation errors if any were raised.
  351. """
  352. exclude = self._get_validation_exclusions()
  353. try:
  354. self.instance.validate_unique(exclude=exclude)
  355. except ValidationError as e:
  356. self._update_errors(e)
  357. def _save_m2m(self):
  358. """
  359. Save the many-to-many fields and generic relations for this form.
  360. """
  361. cleaned_data = self.cleaned_data
  362. exclude = self._meta.exclude
  363. fields = self._meta.fields
  364. opts = self.instance._meta
  365. # Note that for historical reasons we want to include also
  366. # private_fields here. (GenericRelation was previously a fake
  367. # m2m field).
  368. for f in chain(opts.many_to_many, opts.private_fields):
  369. if not hasattr(f, 'save_form_data'):
  370. continue
  371. if fields and f.name not in fields:
  372. continue
  373. if exclude and f.name in exclude:
  374. continue
  375. if f.name in cleaned_data:
  376. f.save_form_data(self.instance, cleaned_data[f.name])
  377. def save(self, commit=True):
  378. """
  379. Save this form's self.instance object if commit=True. Otherwise, add
  380. a save_m2m() method to the form which can be called after the instance
  381. is saved manually at a later time. Return the model instance.
  382. """
  383. if self.errors:
  384. raise ValueError(
  385. "The %s could not be %s because the data didn't validate." % (
  386. self.instance._meta.object_name,
  387. 'created' if self.instance._state.adding else 'changed',
  388. )
  389. )
  390. if commit:
  391. # If committing, save the instance and the m2m data immediately.
  392. self.instance.save()
  393. self._save_m2m()
  394. else:
  395. # If not committing, add a method to the form to allow deferred
  396. # saving of m2m data.
  397. self.save_m2m = self._save_m2m
  398. return self.instance
  399. save.alters_data = True
  400. class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass):
  401. pass
  402. def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
  403. formfield_callback=None, widgets=None, localized_fields=None,
  404. labels=None, help_texts=None, error_messages=None,
  405. field_classes=None):
  406. """
  407. Return a ModelForm containing form fields for the given model. You can
  408. optionally pass a `form` argument to use as a starting point for
  409. constructing the ModelForm.
  410. ``fields`` is an optional list of field names. If provided, include only
  411. the named fields in the returned fields. If omitted or '__all__', use all
  412. fields.
  413. ``exclude`` is an optional list of field names. If provided, exclude the
  414. named fields from the returned fields, even if they are listed in the
  415. ``fields`` argument.
  416. ``widgets`` is a dictionary of model field names mapped to a widget.
  417. ``localized_fields`` is a list of names of fields which should be localized.
  418. ``formfield_callback`` is a callable that takes a model field and returns
  419. a form field.
  420. ``labels`` is a dictionary of model field names mapped to a label.
  421. ``help_texts`` is a dictionary of model field names mapped to a help text.
  422. ``error_messages`` is a dictionary of model field names mapped to a
  423. dictionary of error messages.
  424. ``field_classes`` is a dictionary of model field names mapped to a form
  425. field class.
  426. """
  427. # Create the inner Meta class. FIXME: ideally, we should be able to
  428. # construct a ModelForm without creating and passing in a temporary
  429. # inner class.
  430. # Build up a list of attributes that the Meta object will have.
  431. attrs = {'model': model}
  432. if fields is not None:
  433. attrs['fields'] = fields
  434. if exclude is not None:
  435. attrs['exclude'] = exclude
  436. if widgets is not None:
  437. attrs['widgets'] = widgets
  438. if localized_fields is not None:
  439. attrs['localized_fields'] = localized_fields
  440. if labels is not None:
  441. attrs['labels'] = labels
  442. if help_texts is not None:
  443. attrs['help_texts'] = help_texts
  444. if error_messages is not None:
  445. attrs['error_messages'] = error_messages
  446. if field_classes is not None:
  447. attrs['field_classes'] = field_classes
  448. # If parent form class already has an inner Meta, the Meta we're
  449. # creating needs to inherit from the parent's inner meta.
  450. bases = (form.Meta,) if hasattr(form, 'Meta') else ()
  451. Meta = type('Meta', bases, attrs)
  452. if formfield_callback:
  453. Meta.formfield_callback = staticmethod(formfield_callback)
  454. # Give this new form class a reasonable name.
  455. class_name = model.__name__ + 'Form'
  456. # Class attributes for the new form class.
  457. form_class_attrs = {
  458. 'Meta': Meta,
  459. 'formfield_callback': formfield_callback
  460. }
  461. if (getattr(Meta, 'fields', None) is None and
  462. getattr(Meta, 'exclude', None) is None):
  463. raise ImproperlyConfigured(
  464. "Calling modelform_factory without defining 'fields' or "
  465. "'exclude' explicitly is prohibited."
  466. )
  467. # Instantiate type(form) in order to use the same metaclass as form.
  468. return type(form)(class_name, (form,), form_class_attrs)
  469. # ModelFormSets ##############################################################
  470. class BaseModelFormSet(BaseFormSet):
  471. """
  472. A ``FormSet`` for editing a queryset and/or adding new objects to it.
  473. """
  474. model = None
  475. # Set of fields that must be unique among forms of this set.
  476. unique_fields = set()
  477. def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
  478. queryset=None, *, initial=None, **kwargs):
  479. self.queryset = queryset
  480. self.initial_extra = initial
  481. super().__init__(**{'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix, **kwargs})
  482. def initial_form_count(self):
  483. """Return the number of forms that are required in this FormSet."""
  484. if not self.is_bound:
  485. return len(self.get_queryset())
  486. return super().initial_form_count()
  487. def _existing_object(self, pk):
  488. if not hasattr(self, '_object_dict'):
  489. self._object_dict = {o.pk: o for o in self.get_queryset()}
  490. return self._object_dict.get(pk)
  491. def _get_to_python(self, field):
  492. """
  493. If the field is a related field, fetch the concrete field's (that
  494. is, the ultimate pointed-to field's) to_python.
  495. """
  496. while field.remote_field is not None:
  497. field = field.remote_field.get_related_field()
  498. return field.to_python
  499. def _construct_form(self, i, **kwargs):
  500. pk_required = i < self.initial_form_count()
  501. if pk_required:
  502. if self.is_bound:
  503. pk_key = '%s-%s' % (self.add_prefix(i), self.model._meta.pk.name)
  504. try:
  505. pk = self.data[pk_key]
  506. except KeyError:
  507. # The primary key is missing. The user may have tampered
  508. # with POST data.
  509. pass
  510. else:
  511. to_python = self._get_to_python(self.model._meta.pk)
  512. try:
  513. pk = to_python(pk)
  514. except ValidationError:
  515. # The primary key exists but is an invalid value. The
  516. # user may have tampered with POST data.
  517. pass
  518. else:
  519. kwargs['instance'] = self._existing_object(pk)
  520. else:
  521. kwargs['instance'] = self.get_queryset()[i]
  522. elif self.initial_extra:
  523. # Set initial values for extra forms
  524. try:
  525. kwargs['initial'] = self.initial_extra[i - self.initial_form_count()]
  526. except IndexError:
  527. pass
  528. form = super()._construct_form(i, **kwargs)
  529. if pk_required:
  530. form.fields[self.model._meta.pk.name].required = True
  531. return form
  532. def get_queryset(self):
  533. if not hasattr(self, '_queryset'):
  534. if self.queryset is not None:
  535. qs = self.queryset
  536. else:
  537. qs = self.model._default_manager.get_queryset()
  538. # If the queryset isn't already ordered we need to add an
  539. # artificial ordering here to make sure that all formsets
  540. # constructed from this queryset have the same form order.
  541. if not qs.ordered:
  542. qs = qs.order_by(self.model._meta.pk.name)
  543. # Removed queryset limiting here. As per discussion re: #13023
  544. # on django-dev, max_num should not prevent existing
  545. # related objects/inlines from being displayed.
  546. self._queryset = qs
  547. return self._queryset
  548. def save_new(self, form, commit=True):
  549. """Save and return a new model instance for the given form."""
  550. return form.save(commit=commit)
  551. def save_existing(self, form, instance, commit=True):
  552. """Save and return an existing model instance for the given form."""
  553. return form.save(commit=commit)
  554. def delete_existing(self, obj, commit=True):
  555. """Deletes an existing model instance."""
  556. if commit:
  557. obj.delete()
  558. def save(self, commit=True):
  559. """
  560. Save model instances for every form, adding and changing instances
  561. as necessary, and return the list of instances.
  562. """
  563. if not commit:
  564. self.saved_forms = []
  565. def save_m2m():
  566. for form in self.saved_forms:
  567. form.save_m2m()
  568. self.save_m2m = save_m2m
  569. return self.save_existing_objects(commit) + self.save_new_objects(commit)
  570. save.alters_data = True
  571. def clean(self):
  572. self.validate_unique()
  573. def validate_unique(self):
  574. # Collect unique_checks and date_checks to run from all the forms.
  575. all_unique_checks = set()
  576. all_date_checks = set()
  577. forms_to_delete = self.deleted_forms
  578. valid_forms = [form for form in self.forms if form.is_valid() and form not in forms_to_delete]
  579. for form in valid_forms:
  580. exclude = form._get_validation_exclusions()
  581. unique_checks, date_checks = form.instance._get_unique_checks(exclude=exclude)
  582. all_unique_checks.update(unique_checks)
  583. all_date_checks.update(date_checks)
  584. errors = []
  585. # Do each of the unique checks (unique and unique_together)
  586. for uclass, unique_check in all_unique_checks:
  587. seen_data = set()
  588. for form in valid_forms:
  589. # Get the data for the set of fields that must be unique among the forms.
  590. row_data = (
  591. field if field in self.unique_fields else form.cleaned_data[field]
  592. for field in unique_check if field in form.cleaned_data
  593. )
  594. # Reduce Model instances to their primary key values
  595. row_data = tuple(
  596. d._get_pk_val() if hasattr(d, '_get_pk_val')
  597. # Prevent "unhashable type: list" errors later on.
  598. else tuple(d) if isinstance(d, list)
  599. else d for d in row_data
  600. )
  601. if row_data and None not in row_data:
  602. # if we've already seen it then we have a uniqueness failure
  603. if row_data in seen_data:
  604. # poke error messages into the right places and mark
  605. # the form as invalid
  606. errors.append(self.get_unique_error_message(unique_check))
  607. form._errors[NON_FIELD_ERRORS] = self.error_class([self.get_form_error()])
  608. # remove the data from the cleaned_data dict since it was invalid
  609. for field in unique_check:
  610. if field in form.cleaned_data:
  611. del form.cleaned_data[field]
  612. # mark the data as seen
  613. seen_data.add(row_data)
  614. # iterate over each of the date checks now
  615. for date_check in all_date_checks:
  616. seen_data = set()
  617. uclass, lookup, field, unique_for = date_check
  618. for form in valid_forms:
  619. # see if we have data for both fields
  620. if (form.cleaned_data and form.cleaned_data[field] is not None and
  621. form.cleaned_data[unique_for] is not None):
  622. # if it's a date lookup we need to get the data for all the fields
  623. if lookup == 'date':
  624. date = form.cleaned_data[unique_for]
  625. date_data = (date.year, date.month, date.day)
  626. # otherwise it's just the attribute on the date/datetime
  627. # object
  628. else:
  629. date_data = (getattr(form.cleaned_data[unique_for], lookup),)
  630. data = (form.cleaned_data[field],) + date_data
  631. # if we've already seen it then we have a uniqueness failure
  632. if data in seen_data:
  633. # poke error messages into the right places and mark
  634. # the form as invalid
  635. errors.append(self.get_date_error_message(date_check))
  636. form._errors[NON_FIELD_ERRORS] = self.error_class([self.get_form_error()])
  637. # remove the data from the cleaned_data dict since it was invalid
  638. del form.cleaned_data[field]
  639. # mark the data as seen
  640. seen_data.add(data)
  641. if errors:
  642. raise ValidationError(errors)
  643. def get_unique_error_message(self, unique_check):
  644. if len(unique_check) == 1:
  645. return gettext("Please correct the duplicate data for %(field)s.") % {
  646. "field": unique_check[0],
  647. }
  648. else:
  649. return gettext("Please correct the duplicate data for %(field)s, which must be unique.") % {
  650. "field": get_text_list(unique_check, _("and")),
  651. }
  652. def get_date_error_message(self, date_check):
  653. return gettext(
  654. "Please correct the duplicate data for %(field_name)s "
  655. "which must be unique for the %(lookup)s in %(date_field)s."
  656. ) % {
  657. 'field_name': date_check[2],
  658. 'date_field': date_check[3],
  659. 'lookup': str(date_check[1]),
  660. }
  661. def get_form_error(self):
  662. return gettext("Please correct the duplicate values below.")
  663. def save_existing_objects(self, commit=True):
  664. self.changed_objects = []
  665. self.deleted_objects = []
  666. if not self.initial_forms:
  667. return []
  668. saved_instances = []
  669. forms_to_delete = self.deleted_forms
  670. for form in self.initial_forms:
  671. obj = form.instance
  672. # If the pk is None, it means either:
  673. # 1. The object is an unexpected empty model, created by invalid
  674. # POST data such as an object outside the formset's queryset.
  675. # 2. The object was already deleted from the database.
  676. if obj.pk is None:
  677. continue
  678. if form in forms_to_delete:
  679. self.deleted_objects.append(obj)
  680. self.delete_existing(obj, commit=commit)
  681. elif form.has_changed():
  682. self.changed_objects.append((obj, form.changed_data))
  683. saved_instances.append(self.save_existing(form, obj, commit=commit))
  684. if not commit:
  685. self.saved_forms.append(form)
  686. return saved_instances
  687. def save_new_objects(self, commit=True):
  688. self.new_objects = []
  689. for form in self.extra_forms:
  690. if not form.has_changed():
  691. continue
  692. # If someone has marked an add form for deletion, don't save the
  693. # object.
  694. if self.can_delete and self._should_delete_form(form):
  695. continue
  696. self.new_objects.append(self.save_new(form, commit=commit))
  697. if not commit:
  698. self.saved_forms.append(form)
  699. return self.new_objects
  700. def add_fields(self, form, index):
  701. """Add a hidden field for the object's primary key."""
  702. from django.db.models import AutoField, OneToOneField, ForeignKey
  703. self._pk_field = pk = self.model._meta.pk
  704. # If a pk isn't editable, then it won't be on the form, so we need to
  705. # add it here so we can tell which object is which when we get the
  706. # data back. Generally, pk.editable should be false, but for some
  707. # reason, auto_created pk fields and AutoField's editable attribute is
  708. # True, so check for that as well.
  709. def pk_is_not_editable(pk):
  710. return (
  711. (not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or (
  712. pk.remote_field and pk.remote_field.parent_link and
  713. pk_is_not_editable(pk.remote_field.model._meta.pk)
  714. )
  715. )
  716. if pk_is_not_editable(pk) or pk.name not in form.fields:
  717. if form.is_bound:
  718. # If we're adding the related instance, ignore its primary key
  719. # as it could be an auto-generated default which isn't actually
  720. # in the database.
  721. pk_value = None if form.instance._state.adding else form.instance.pk
  722. else:
  723. try:
  724. if index is not None:
  725. pk_value = self.get_queryset()[index].pk
  726. else:
  727. pk_value = None
  728. except IndexError:
  729. pk_value = None
  730. if isinstance(pk, (ForeignKey, OneToOneField)):
  731. qs = pk.remote_field.model._default_manager.get_queryset()
  732. else:
  733. qs = self.model._default_manager.get_queryset()
  734. qs = qs.using(form.instance._state.db)
  735. if form._meta.widgets:
  736. widget = form._meta.widgets.get(self._pk_field.name, HiddenInput)
  737. else:
  738. widget = HiddenInput
  739. form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=widget)
  740. super().add_fields(form, index)
  741. def modelformset_factory(model, form=ModelForm, formfield_callback=None,
  742. formset=BaseModelFormSet, extra=1, can_delete=False,
  743. can_order=False, max_num=None, fields=None, exclude=None,
  744. widgets=None, validate_max=False, localized_fields=None,
  745. labels=None, help_texts=None, error_messages=None,
  746. min_num=None, validate_min=False, field_classes=None):
  747. """Return a FormSet class for the given Django model class."""
  748. meta = getattr(form, 'Meta', None)
  749. if (getattr(meta, 'fields', fields) is None and
  750. getattr(meta, 'exclude', exclude) is None):
  751. raise ImproperlyConfigured(
  752. "Calling modelformset_factory without defining 'fields' or "
  753. "'exclude' explicitly is prohibited."
  754. )
  755. form = modelform_factory(model, form=form, fields=fields, exclude=exclude,
  756. formfield_callback=formfield_callback,
  757. widgets=widgets, localized_fields=localized_fields,
  758. labels=labels, help_texts=help_texts,
  759. error_messages=error_messages, field_classes=field_classes)
  760. FormSet = formset_factory(form, formset, extra=extra, min_num=min_num, max_num=max_num,
  761. can_order=can_order, can_delete=can_delete,
  762. validate_min=validate_min, validate_max=validate_max)
  763. FormSet.model = model
  764. return FormSet
  765. # InlineFormSets #############################################################
  766. class BaseInlineFormSet(BaseModelFormSet):
  767. """A formset for child objects related to a parent."""
  768. def __init__(self, data=None, files=None, instance=None,
  769. save_as_new=False, prefix=None, queryset=None, **kwargs):
  770. if instance is None:
  771. self.instance = self.fk.remote_field.model()
  772. else:
  773. self.instance = instance
  774. self.save_as_new = save_as_new
  775. if queryset is None:
  776. queryset = self.model._default_manager
  777. if self.instance.pk is not None:
  778. qs = queryset.filter(**{self.fk.name: self.instance})
  779. else:
  780. qs = queryset.none()
  781. self.unique_fields = {self.fk.name}
  782. super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
  783. # Add the generated field to form._meta.fields if it's defined to make
  784. # sure validation isn't skipped on that field.
  785. if self.form._meta.fields and self.fk.name not in self.form._meta.fields:
  786. if isinstance(self.form._meta.fields, tuple):
  787. self.form._meta.fields = list(self.form._meta.fields)
  788. self.form._meta.fields.append(self.fk.name)
  789. def initial_form_count(self):
  790. if self.save_as_new:
  791. return 0
  792. return super().initial_form_count()
  793. def _construct_form(self, i, **kwargs):
  794. form = super()._construct_form(i, **kwargs)
  795. if self.save_as_new:
  796. mutable = getattr(form.data, '_mutable', None)
  797. # Allow modifying an immutable QueryDict.
  798. if mutable is not None:
  799. form.data._mutable = True
  800. # Remove the primary key from the form's data, we are only
  801. # creating new instances
  802. form.data[form.add_prefix(self._pk_field.name)] = None
  803. # Remove the foreign key from the form's data
  804. form.data[form.add_prefix(self.fk.name)] = None
  805. if mutable is not None:
  806. form.data._mutable = mutable
  807. # Set the fk value here so that the form can do its validation.
  808. fk_value = self.instance.pk
  809. if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name:
  810. fk_value = getattr(self.instance, self.fk.remote_field.field_name)
  811. fk_value = getattr(fk_value, 'pk', fk_value)
  812. setattr(form.instance, self.fk.get_attname(), fk_value)
  813. return form
  814. @classmethod
  815. def get_default_prefix(cls):
  816. return cls.fk.remote_field.get_accessor_name(model=cls.model).replace('+', '')
  817. def save_new(self, form, commit=True):
  818. # Ensure the latest copy of the related instance is present on each
  819. # form (it may have been saved after the formset was originally
  820. # instantiated).
  821. setattr(form.instance, self.fk.name, self.instance)
  822. return super().save_new(form, commit=commit)
  823. def add_fields(self, form, index):
  824. super().add_fields(form, index)
  825. if self._pk_field == self.fk:
  826. name = self._pk_field.name
  827. kwargs = {'pk_field': True}
  828. else:
  829. # The foreign key field might not be on the form, so we poke at the
  830. # Model field to get the label, since we need that for error messages.
  831. name = self.fk.name
  832. kwargs = {
  833. 'label': getattr(form.fields.get(name), 'label', capfirst(self.fk.verbose_name))
  834. }
  835. # The InlineForeignKeyField assumes that the foreign key relation is
  836. # based on the parent model's pk. If this isn't the case, set to_field
  837. # to correctly resolve the initial form value.
  838. if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name:
  839. kwargs['to_field'] = self.fk.remote_field.field_name
  840. # If we're adding a new object, ignore a parent's auto-generated key
  841. # as it will be regenerated on the save request.
  842. if self.instance._state.adding:
  843. if kwargs.get('to_field') is not None:
  844. to_field = self.instance._meta.get_field(kwargs['to_field'])
  845. else:
  846. to_field = self.instance._meta.pk
  847. if to_field.has_default():
  848. setattr(self.instance, to_field.attname, None)
  849. form.fields[name] = InlineForeignKeyField(self.instance, **kwargs)
  850. def get_unique_error_message(self, unique_check):
  851. unique_check = [field for field in unique_check if field != self.fk.name]
  852. return super().get_unique_error_message(unique_check)
  853. def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
  854. """
  855. Find and return the ForeignKey from model to parent if there is one
  856. (return None if can_fail is True and no such field exists). If fk_name is
  857. provided, assume it is the name of the ForeignKey field. Unless can_fail is
  858. True, raise an exception if there isn't a ForeignKey from model to
  859. parent_model.
  860. """
  861. # avoid circular import
  862. from django.db.models import ForeignKey
  863. opts = model._meta
  864. if fk_name:
  865. fks_to_parent = [f for f in opts.fields if f.name == fk_name]
  866. if len(fks_to_parent) == 1:
  867. fk = fks_to_parent[0]
  868. if not isinstance(fk, ForeignKey) or \
  869. (fk.remote_field.model != parent_model and
  870. fk.remote_field.model not in parent_model._meta.get_parent_list()):
  871. raise ValueError(
  872. "fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, parent_model._meta.label)
  873. )
  874. elif not fks_to_parent:
  875. raise ValueError(
  876. "'%s' has no field named '%s'." % (model._meta.label, fk_name)
  877. )
  878. else:
  879. # Try to discover what the ForeignKey from model to parent_model is
  880. fks_to_parent = [
  881. f for f in opts.fields
  882. if isinstance(f, ForeignKey) and (
  883. f.remote_field.model == parent_model or
  884. f.remote_field.model in parent_model._meta.get_parent_list()
  885. )
  886. ]
  887. if len(fks_to_parent) == 1:
  888. fk = fks_to_parent[0]
  889. elif not fks_to_parent:
  890. if can_fail:
  891. return
  892. raise ValueError(
  893. "'%s' has no ForeignKey to '%s'." % (
  894. model._meta.label,
  895. parent_model._meta.label,
  896. )
  897. )
  898. else:
  899. raise ValueError(
  900. "'%s' has more than one ForeignKey to '%s'." % (
  901. model._meta.label,
  902. parent_model._meta.label,
  903. )
  904. )
  905. return fk
  906. def inlineformset_factory(parent_model, model, form=ModelForm,
  907. formset=BaseInlineFormSet, fk_name=None,
  908. fields=None, exclude=None, extra=3, can_order=False,
  909. can_delete=True, max_num=None, formfield_callback=None,
  910. widgets=None, validate_max=False, localized_fields=None,
  911. labels=None, help_texts=None, error_messages=None,
  912. min_num=None, validate_min=False, field_classes=None):
  913. """
  914. Return an ``InlineFormSet`` for the given kwargs.
  915. ``fk_name`` must be provided if ``model`` has more than one ``ForeignKey``
  916. to ``parent_model``.
  917. """
  918. fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
  919. # enforce a max_num=1 when the foreign key to the parent model is unique.
  920. if fk.unique:
  921. max_num = 1
  922. kwargs = {
  923. 'form': form,
  924. 'formfield_callback': formfield_callback,
  925. 'formset': formset,
  926. 'extra': extra,
  927. 'can_delete': can_delete,
  928. 'can_order': can_order,
  929. 'fields': fields,
  930. 'exclude': exclude,
  931. 'min_num': min_num,
  932. 'max_num': max_num,
  933. 'widgets': widgets,
  934. 'validate_min': validate_min,
  935. 'validate_max': validate_max,
  936. 'localized_fields': localized_fields,
  937. 'labels': labels,
  938. 'help_texts': help_texts,
  939. 'error_messages': error_messages,
  940. 'field_classes': field_classes,
  941. }
  942. FormSet = modelformset_factory(model, **kwargs)
  943. FormSet.fk = fk
  944. return FormSet
  945. # Fields #####################################################################
  946. class InlineForeignKeyField(Field):
  947. """
  948. A basic integer field that deals with validating the given value to a
  949. given parent instance in an inline.
  950. """
  951. widget = HiddenInput
  952. default_error_messages = {
  953. 'invalid_choice': _('The inline value did not match the parent instance.'),
  954. }
  955. def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):
  956. self.parent_instance = parent_instance
  957. self.pk_field = pk_field
  958. self.to_field = to_field
  959. if self.parent_instance is not None:
  960. if self.to_field:
  961. kwargs["initial"] = getattr(self.parent_instance, self.to_field)
  962. else:
  963. kwargs["initial"] = self.parent_instance.pk
  964. kwargs["required"] = False
  965. super().__init__(*args, **kwargs)
  966. def clean(self, value):
  967. if value in self.empty_values:
  968. if self.pk_field:
  969. return None
  970. # if there is no value act as we did before.
  971. return self.parent_instance
  972. # ensure the we compare the values as equal types.
  973. if self.to_field:
  974. orig = getattr(self.parent_instance, self.to_field)
  975. else:
  976. orig = self.parent_instance.pk
  977. if str(value) != str(orig):
  978. raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
  979. return self.parent_instance
  980. def has_changed(self, initial, data):
  981. return False
  982. class ModelChoiceIterator:
  983. def __init__(self, field):
  984. self.field = field
  985. self.queryset = field.queryset
  986. def __iter__(self):
  987. if self.field.empty_label is not None:
  988. yield ("", self.field.empty_label)
  989. queryset = self.queryset
  990. # Can't use iterator() when queryset uses prefetch_related()
  991. if not queryset._prefetch_related_lookups:
  992. queryset = queryset.iterator()
  993. for obj in queryset:
  994. yield self.choice(obj)
  995. def __len__(self):
  996. # count() adds a query but uses less memory since the QuerySet results
  997. # won't be cached. In most cases, the choices will only be iterated on,
  998. # and __len__() won't be called.
  999. return self.queryset.count() + (1 if self.field.empty_label is not None else 0)
  1000. def __bool__(self):
  1001. return self.field.empty_label is not None or self.queryset.exists()
  1002. def choice(self, obj):
  1003. return (self.field.prepare_value(obj), self.field.label_from_instance(obj))
  1004. class ModelChoiceField(ChoiceField):
  1005. """A ChoiceField whose choices are a model QuerySet."""
  1006. # This class is a subclass of ChoiceField for purity, but it doesn't
  1007. # actually use any of ChoiceField's implementation.
  1008. default_error_messages = {
  1009. 'invalid_choice': _('Select a valid choice. That choice is not one of'
  1010. ' the available choices.'),
  1011. }
  1012. iterator = ModelChoiceIterator
  1013. def __init__(self, queryset, *, empty_label="---------",
  1014. required=True, widget=None, label=None, initial=None,
  1015. help_text='', to_field_name=None, limit_choices_to=None,
  1016. **kwargs):
  1017. if required and (initial is not None):
  1018. self.empty_label = None
  1019. else:
  1020. self.empty_label = empty_label
  1021. # Call Field instead of ChoiceField __init__() because we don't need
  1022. # ChoiceField.__init__().
  1023. Field.__init__(
  1024. self, required=required, widget=widget, label=label,
  1025. initial=initial, help_text=help_text, **kwargs
  1026. )
  1027. self.queryset = queryset
  1028. self.limit_choices_to = limit_choices_to # limit the queryset later.
  1029. self.to_field_name = to_field_name
  1030. def get_limit_choices_to(self):
  1031. """
  1032. Return ``limit_choices_to`` for this form field.
  1033. If it is a callable, invoke it and return the result.
  1034. """
  1035. if callable(self.limit_choices_to):
  1036. return self.limit_choices_to()
  1037. return self.limit_choices_to
  1038. def __deepcopy__(self, memo):
  1039. result = super(ChoiceField, self).__deepcopy__(memo)
  1040. # Need to force a new ModelChoiceIterator to be created, bug #11183
  1041. if self.queryset is not None:
  1042. result.queryset = self.queryset.all()
  1043. return result
  1044. def _get_queryset(self):
  1045. return self._queryset
  1046. def _set_queryset(self, queryset):
  1047. self._queryset = None if queryset is None else queryset.all()
  1048. self.widget.choices = self.choices
  1049. queryset = property(_get_queryset, _set_queryset)
  1050. # this method will be used to create object labels by the QuerySetIterator.
  1051. # Override it to customize the label.
  1052. def label_from_instance(self, obj):
  1053. """
  1054. Convert objects into strings and generate the labels for the choices
  1055. presented by this object. Subclasses can override this method to
  1056. customize the display of the choices.
  1057. """
  1058. return str(obj)
  1059. def _get_choices(self):
  1060. # If self._choices is set, then somebody must have manually set
  1061. # the property self.choices. In this case, just return self._choices.
  1062. if hasattr(self, '_choices'):
  1063. return self._choices
  1064. # Otherwise, execute the QuerySet in self.queryset to determine the
  1065. # choices dynamically. Return a fresh ModelChoiceIterator that has not been
  1066. # consumed. Note that we're instantiating a new ModelChoiceIterator *each*
  1067. # time _get_choices() is called (and, thus, each time self.choices is
  1068. # accessed) so that we can ensure the QuerySet has not been consumed. This
  1069. # construct might look complicated but it allows for lazy evaluation of
  1070. # the queryset.
  1071. return self.iterator(self)
  1072. choices = property(_get_choices, ChoiceField._set_choices)
  1073. def prepare_value(self, value):
  1074. if hasattr(value, '_meta'):
  1075. if self.to_field_name:
  1076. return value.serializable_value(self.to_field_name)
  1077. else:
  1078. return value.pk
  1079. return super().prepare_value(value)
  1080. def to_python(self, value):
  1081. if value in self.empty_values:
  1082. return None
  1083. try:
  1084. key = self.to_field_name or 'pk'
  1085. if isinstance(value, self.queryset.model):
  1086. value = getattr(value, key)
  1087. value = self.queryset.get(**{key: value})
  1088. except (ValueError, TypeError, self.queryset.model.DoesNotExist):
  1089. raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
  1090. return value
  1091. def validate(self, value):
  1092. return Field.validate(self, value)
  1093. def has_changed(self, initial, data):
  1094. if self.disabled:
  1095. return False
  1096. initial_value = initial if initial is not None else ''
  1097. data_value = data if data is not None else ''
  1098. return str(self.prepare_value(initial_value)) != str(data_value)
  1099. class ModelMultipleChoiceField(ModelChoiceField):
  1100. """A MultipleChoiceField whose choices are a model QuerySet."""
  1101. widget = SelectMultiple
  1102. hidden_widget = MultipleHiddenInput
  1103. default_error_messages = {
  1104. 'list': _('Enter a list of values.'),
  1105. 'invalid_choice': _('Select a valid choice. %(value)s is not one of the'
  1106. ' available choices.'),
  1107. 'invalid_pk_value': _('“%(pk)s” is not a valid value.')
  1108. }
  1109. def __init__(self, queryset, **kwargs):
  1110. super().__init__(queryset, empty_label=None, **kwargs)
  1111. def to_python(self, value):
  1112. if not value:
  1113. return []
  1114. return list(self._check_values(value))
  1115. def clean(self, value):
  1116. value = self.prepare_value(value)
  1117. if self.required and not value:
  1118. raise ValidationError(self.error_messages['required'], code='required')
  1119. elif not self.required and not value:
  1120. return self.queryset.none()
  1121. if not isinstance(value, (list, tuple)):
  1122. raise ValidationError(self.error_messages['list'], code='list')
  1123. qs = self._check_values(value)
  1124. # Since this overrides the inherited ModelChoiceField.clean
  1125. # we run custom validators here
  1126. self.run_validators(value)
  1127. return qs
  1128. def _check_values(self, value):
  1129. """
  1130. Given a list of possible PK values, return a QuerySet of the
  1131. corresponding objects. Raise a ValidationError if a given value is
  1132. invalid (not a valid PK, not in the queryset, etc.)
  1133. """
  1134. key = self.to_field_name or 'pk'
  1135. # deduplicate given values to avoid creating many querysets or
  1136. # requiring the database backend deduplicate efficiently.
  1137. try:
  1138. value = frozenset(value)
  1139. except TypeError:
  1140. # list of lists isn't hashable, for example
  1141. raise ValidationError(
  1142. self.error_messages['list'],
  1143. code='list',
  1144. )
  1145. for pk in value:
  1146. try:
  1147. self.queryset.filter(**{key: pk})
  1148. except (ValueError, TypeError):
  1149. raise ValidationError(
  1150. self.error_messages['invalid_pk_value'],
  1151. code='invalid_pk_value',
  1152. params={'pk': pk},
  1153. )
  1154. qs = self.queryset.filter(**{'%s__in' % key: value})
  1155. pks = {str(getattr(o, key)) for o in qs}
  1156. for val in value:
  1157. if str(val) not in pks:
  1158. raise ValidationError(
  1159. self.error_messages['invalid_choice'],
  1160. code='invalid_choice',
  1161. params={'value': val},
  1162. )
  1163. return qs
  1164. def prepare_value(self, value):
  1165. if (hasattr(value, '__iter__') and
  1166. not isinstance(value, str) and
  1167. not hasattr(value, '_meta')):
  1168. prepare_value = super().prepare_value
  1169. return [prepare_value(v) for v in value]
  1170. return super().prepare_value(value)
  1171. def has_changed(self, initial, data):
  1172. if self.disabled:
  1173. return False
  1174. if initial is None:
  1175. initial = []
  1176. if data is None:
  1177. data = []
  1178. if len(initial) != len(data):
  1179. return True
  1180. initial_set = {str(value) for value in self.prepare_value(initial)}
  1181. data_set = {str(value) for value in data}
  1182. return data_set != initial_set
  1183. def modelform_defines_fields(form_class):
  1184. return hasattr(form_class, '_meta') and (
  1185. form_class._meta.fields is not None or
  1186. form_class._meta.exclude is not None
  1187. )