models.py 56 KB

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