models.py 59 KB

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