You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 54 KiB

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