models.py 44 KB

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