Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 59KB

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