models.py 60 KB

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