models.py 59 KB

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