You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 55KB

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