models.py 59 KB

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