models.py 53 KB

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