models.py 43 KB

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