models.py 61 KB

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