models.py 51 KB

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