modelforms.txt 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. ==========================
  2. Creating forms from models
  3. ==========================
  4. .. module:: django.forms.models
  5. :synopsis: ModelForm and ModelFormset.
  6. .. currentmodule:: django.forms
  7. ``ModelForm``
  8. =============
  9. .. class:: ModelForm
  10. If you're building a database-driven app, chances are you'll have forms that
  11. map closely to Django models. For instance, you might have a ``BlogComment``
  12. model, and you want to create a form that lets people submit comments. In this
  13. case, it would be redundant to define the field types in your form, because
  14. you've already defined the fields in your model.
  15. For this reason, Django provides a helper class that let you create a ``Form``
  16. class from a Django model.
  17. For example::
  18. >>> from django.forms import ModelForm
  19. # Create the form class.
  20. >>> class ArticleForm(ModelForm):
  21. ... class Meta:
  22. ... model = Article
  23. ... fields = ['pub_date', 'headline', 'content', 'reporter']
  24. # Creating a form to add an article.
  25. >>> form = ArticleForm()
  26. # Creating a form to change an existing article.
  27. >>> article = Article.objects.get(pk=1)
  28. >>> form = ArticleForm(instance=article)
  29. Field types
  30. -----------
  31. The generated ``Form`` class will have a form field for every model field
  32. specified, in the order specified in the ``fields`` attribute.
  33. Each model field has a corresponding default form field. For example, a
  34. ``CharField`` on a model is represented as a ``CharField`` on a form. A model
  35. ``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is the
  36. full list of conversions:
  37. =============================== ========================================
  38. Model field Form field
  39. =============================== ========================================
  40. ``AutoField`` Not represented in the form
  41. ``BigIntegerField`` ``IntegerField`` with ``min_value`` set
  42. to -9223372036854775808 and ``max_value``
  43. set to 9223372036854775807.
  44. ``BooleanField`` ``BooleanField``
  45. ``CharField`` ``CharField`` with ``max_length`` set to
  46. the model field's ``max_length``
  47. ``CommaSeparatedIntegerField`` ``CharField``
  48. ``DateField`` ``DateField``
  49. ``DateTimeField`` ``DateTimeField``
  50. ``DecimalField`` ``DecimalField``
  51. ``EmailField`` ``EmailField``
  52. ``FileField`` ``FileField``
  53. ``FilePathField`` ``CharField``
  54. ``FloatField`` ``FloatField``
  55. ``ForeignKey`` ``ModelChoiceField`` (see below)
  56. ``ImageField`` ``ImageField``
  57. ``IntegerField`` ``IntegerField``
  58. ``IPAddressField`` ``IPAddressField``
  59. ``GenericIPAddressField`` ``GenericIPAddressField``
  60. ``ManyToManyField`` ``ModelMultipleChoiceField`` (see
  61. below)
  62. ``NullBooleanField`` ``CharField``
  63. ``PositiveIntegerField`` ``IntegerField``
  64. ``PositiveSmallIntegerField`` ``IntegerField``
  65. ``SlugField`` ``SlugField``
  66. ``SmallIntegerField`` ``IntegerField``
  67. ``TextField`` ``CharField`` with
  68. ``widget=forms.Textarea``
  69. ``TimeField`` ``TimeField``
  70. ``URLField`` ``URLField``
  71. =============================== ========================================
  72. As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field
  73. types are special cases:
  74. * ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``,
  75. which is a ``ChoiceField`` whose choices are a model ``QuerySet``.
  76. * ``ManyToManyField`` is represented by
  77. ``django.forms.ModelMultipleChoiceField``, which is a
  78. ``MultipleChoiceField`` whose choices are a model ``QuerySet``.
  79. In addition, each generated form field has attributes set as follows:
  80. * If the model field has ``blank=True``, then ``required`` is set to
  81. ``False`` on the form field. Otherwise, ``required=True``.
  82. * The form field's ``label`` is set to the ``verbose_name`` of the model
  83. field, with the first character capitalized.
  84. * The form field's ``help_text`` is set to the ``help_text`` of the model
  85. field.
  86. * If the model field has ``choices`` set, then the form field's ``widget``
  87. will be set to ``Select``, with choices coming from the model field's
  88. ``choices``. The choices will normally include the blank choice which is
  89. selected by default. If the field is required, this forces the user to
  90. make a selection. The blank choice will not be included if the model
  91. field has ``blank=False`` and an explicit ``default`` value (the
  92. ``default`` value will be initially selected instead).
  93. Finally, note that you can override the form field used for a given model
  94. field. See `Overriding the default field types or widgets`_ below.
  95. A full example
  96. --------------
  97. Consider this set of models::
  98. from django.db import models
  99. from django.forms import ModelForm
  100. TITLE_CHOICES = (
  101. ('MR', 'Mr.'),
  102. ('MRS', 'Mrs.'),
  103. ('MS', 'Ms.'),
  104. )
  105. class Author(models.Model):
  106. name = models.CharField(max_length=100)
  107. title = models.CharField(max_length=3, choices=TITLE_CHOICES)
  108. birth_date = models.DateField(blank=True, null=True)
  109. def __unicode__(self):
  110. return self.name
  111. class Book(models.Model):
  112. name = models.CharField(max_length=100)
  113. authors = models.ManyToManyField(Author)
  114. class AuthorForm(ModelForm):
  115. class Meta:
  116. model = Author
  117. fields = ['name', 'title', 'birth_date']
  118. class BookForm(ModelForm):
  119. class Meta:
  120. model = Book
  121. fields = ['name', 'authors']
  122. With these models, the ``ModelForm`` subclasses above would be roughly
  123. equivalent to this (the only difference being the ``save()`` method, which
  124. we'll discuss in a moment.)::
  125. from django import forms
  126. class AuthorForm(forms.Form):
  127. name = forms.CharField(max_length=100)
  128. title = forms.CharField(max_length=3,
  129. widget=forms.Select(choices=TITLE_CHOICES))
  130. birth_date = forms.DateField(required=False)
  131. class BookForm(forms.Form):
  132. name = forms.CharField(max_length=100)
  133. authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
  134. .. _modelform-is-valid-and-errors:
  135. The ``is_valid()`` method and ``errors``
  136. ----------------------------------------
  137. The first time you call ``is_valid()`` or access the ``errors`` attribute of a
  138. ``ModelForm`` triggers :ref:`form validation <form-and-field-validation>` as
  139. well as :ref:`model validation <validating-objects>`. This has the side-effect
  140. of cleaning the model you pass to the ``ModelForm`` constructor. For instance,
  141. calling ``is_valid()`` on your form will convert any date fields on your model
  142. to actual date objects. If form validation fails, only some of the updates
  143. may be applied. For this reason, you'll probably want to avoid reusing the
  144. model instance passed to the form, especially if validation fails.
  145. The ``save()`` method
  146. ---------------------
  147. Every form produced by ``ModelForm`` also has a ``save()``
  148. method. This method creates and saves a database object from the data
  149. bound to the form. A subclass of ``ModelForm`` can accept an existing
  150. model instance as the keyword argument ``instance``; if this is
  151. supplied, ``save()`` will update that instance. If it's not supplied,
  152. ``save()`` will create a new instance of the specified model:
  153. .. code-block:: python
  154. # Create a form instance from POST data.
  155. >>> f = ArticleForm(request.POST)
  156. # Save a new Article object from the form's data.
  157. >>> new_article = f.save()
  158. # Create a form to edit an existing Article, but use
  159. # POST data to populate the form.
  160. >>> a = Article.objects.get(pk=1)
  161. >>> f = ArticleForm(request.POST, instance=a)
  162. >>> f.save()
  163. Note that if the form :ref:`hasn't been validated
  164. <modelform-is-valid-and-errors>`, calling ``save()`` will do so by checking
  165. ``form.errors``. A ``ValueError`` will be raised if the data in the form
  166. doesn't validate -- i.e., if ``form.errors`` evaluates to ``True``.
  167. This ``save()`` method accepts an optional ``commit`` keyword argument, which
  168. accepts either ``True`` or ``False``. If you call ``save()`` with
  169. ``commit=False``, then it will return an object that hasn't yet been saved to
  170. the database. In this case, it's up to you to call ``save()`` on the resulting
  171. model instance. This is useful if you want to do custom processing on the
  172. object before saving it, or if you want to use one of the specialized
  173. :ref:`model saving options <ref-models-force-insert>`. ``commit`` is ``True``
  174. by default.
  175. Another side effect of using ``commit=False`` is seen when your model has
  176. a many-to-many relation with another model. If your model has a many-to-many
  177. relation and you specify ``commit=False`` when you save a form, Django cannot
  178. immediately save the form data for the many-to-many relation. This is because
  179. it isn't possible to save many-to-many data for an instance until the instance
  180. exists in the database.
  181. To work around this problem, every time you save a form using ``commit=False``,
  182. Django adds a ``save_m2m()`` method to your ``ModelForm`` subclass. After
  183. you've manually saved the instance produced by the form, you can invoke
  184. ``save_m2m()`` to save the many-to-many form data. For example::
  185. # Create a form instance with POST data.
  186. >>> f = AuthorForm(request.POST)
  187. # Create, but don't save the new author instance.
  188. >>> new_author = f.save(commit=False)
  189. # Modify the author in some way.
  190. >>> new_author.some_field = 'some_value'
  191. # Save the new instance.
  192. >>> new_author.save()
  193. # Now, save the many-to-many data for the form.
  194. >>> f.save_m2m()
  195. Calling ``save_m2m()`` is only required if you use ``save(commit=False)``.
  196. When you use a simple ``save()`` on a form, all data -- including
  197. many-to-many data -- is saved without the need for any additional method calls.
  198. For example::
  199. # Create a form instance with POST data.
  200. >>> a = Author()
  201. >>> f = AuthorForm(request.POST, instance=a)
  202. # Create and save the new author instance. There's no need to do anything else.
  203. >>> new_author = f.save()
  204. Other than the ``save()`` and ``save_m2m()`` methods, a ``ModelForm`` works
  205. exactly the same way as any other ``forms`` form. For example, the
  206. ``is_valid()`` method is used to check for validity, the ``is_multipart()``
  207. method is used to determine whether a form requires multipart file upload (and
  208. hence whether ``request.FILES`` must be passed to the form), etc. See
  209. :ref:`binding-uploaded-files` for more information.
  210. .. _modelforms-selecting-fields:
  211. Selecting the fields to use
  212. ---------------------------
  213. It is strongly recommended that you explicitly set all fields that should be
  214. edited in the form using the ``fields`` attribute. Failure to do so can easily
  215. lead to security problems when a form unexpectedly allows a user to set certain
  216. fields, especially when new fields are added to a model. Depending on how the
  217. form is rendered, the problem may not even be visible on the web page.
  218. The alternative approach would be to include all fields automatically, or
  219. blacklist only some. This fundamental approach is known to be much less secure
  220. and has led to serious exploits on major websites (e.g. `GitHub
  221. <https://github.com/blog/1068-public-key-security-vulnerability-and-mitigation>`_).
  222. There are, however, two shortcuts available for cases where you can guarantee
  223. these security concerns do not apply to you:
  224. 1. Set the ``fields`` attribute to the special value ``'__all__'`` to indicate
  225. that all fields in the model should be used. For example::
  226. class AuthorForm(ModelForm):
  227. class Meta:
  228. model = Author
  229. fields = '__all__'
  230. 2. Set the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta`` class to
  231. a list of fields to be excluded from the form.
  232. For example::
  233. class PartialAuthorForm(ModelForm):
  234. class Meta:
  235. model = Author
  236. exclude = ['title']
  237. Since the ``Author`` model has the 3 fields ``name``, ``title`` and
  238. ``birth_date``, this will result in the fields ``name`` and ``birth_date``
  239. being present on the form.
  240. If either of these are used, the order the fields appear in the form will be the
  241. order the fields are defined in the model, with ``ManyToManyField`` instances
  242. appearing last.
  243. In addition, Django applies the following rule: if you set ``editable=False`` on
  244. the model field, *any* form created from the model via ``ModelForm`` will not
  245. include that field.
  246. .. versionchanged:: 1.6
  247. Before version 1.6, the ``'__all__'`` shortcut did not exist, but omitting
  248. the ``fields`` attribute had the same effect. Omitting both ``fields`` and
  249. ``exclude`` is now deprecated, but will continue to work as before until
  250. version 1.8
  251. .. note::
  252. Any fields not included in a form by the above logic
  253. will not be set by the form's ``save()`` method. Also, if you
  254. manually add the excluded fields back to the form, they will not
  255. be initialized from the model instance.
  256. Django will prevent any attempt to save an incomplete model, so if
  257. the model does not allow the missing fields to be empty, and does
  258. not provide a default value for the missing fields, any attempt to
  259. ``save()`` a ``ModelForm`` with missing fields will fail. To
  260. avoid this failure, you must instantiate your model with initial
  261. values for the missing, but required fields::
  262. author = Author(title='Mr')
  263. form = PartialAuthorForm(request.POST, instance=author)
  264. form.save()
  265. Alternatively, you can use ``save(commit=False)`` and manually set
  266. any extra required fields::
  267. form = PartialAuthorForm(request.POST)
  268. author = form.save(commit=False)
  269. author.title = 'Mr'
  270. author.save()
  271. See the `section on saving forms`_ for more details on using
  272. ``save(commit=False)``.
  273. .. _section on saving forms: `The save() method`_
  274. Overriding the default field types or widgets
  275. ---------------------------------------------
  276. The default field types, as described in the `Field types`_ table above, are
  277. sensible defaults. If you have a ``DateField`` in your model, chances are you'd
  278. want that to be represented as a ``DateField`` in your form. But
  279. ``ModelForm`` gives you the flexibility of changing the form field type and
  280. widget for a given model field.
  281. To specify a custom widget for a field, use the ``widgets`` attribute of the
  282. inner ``Meta`` class. This should be a dictionary mapping field names to widget
  283. classes or instances.
  284. For example, if you want the a ``CharField`` for the ``name``
  285. attribute of ``Author`` to be represented by a ``<textarea>`` instead
  286. of its default ``<input type="text">``, you can override the field's
  287. widget::
  288. from django.forms import ModelForm, Textarea
  289. class AuthorForm(ModelForm):
  290. class Meta:
  291. model = Author
  292. fields = ('name', 'title', 'birth_date')
  293. widgets = {
  294. 'name': Textarea(attrs={'cols': 80, 'rows': 20}),
  295. }
  296. The ``widgets`` dictionary accepts either widget instances (e.g.,
  297. ``Textarea(...)``) or classes (e.g., ``Textarea``).
  298. If you want to further customize a field -- including its type, label, etc. --
  299. you can do this by declaratively specifying fields like you would in a regular
  300. ``Form``. Declared fields will override the default ones generated by using the
  301. ``model`` attribute.
  302. For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
  303. field, you could do the following::
  304. class ArticleForm(ModelForm):
  305. pub_date = MyDateFormField()
  306. class Meta:
  307. model = Article
  308. fields = ['pub_date', 'headline', 'content', 'reporter']
  309. If you want to override a field's default label, then specify the ``label``
  310. parameter when declaring the form field::
  311. class ArticleForm(ModelForm):
  312. pub_date = DateField(label='Publication date')
  313. class Meta:
  314. model = Article
  315. fields = ['pub_date', 'headline', 'content', 'reporter']
  316. .. note::
  317. If you explicitly instantiate a form field like this, Django assumes that you
  318. want to completely define its behavior; therefore, default attributes (such as
  319. ``max_length`` or ``required``) are not drawn from the corresponding model. If
  320. you want to maintain the behavior specified in the model, you must set the
  321. relevant arguments explicitly when declaring the form field.
  322. For example, if the ``Article`` model looks like this::
  323. class Article(models.Model):
  324. headline = models.CharField(max_length=200, null=True, blank=True,
  325. help_text="Use puns liberally")
  326. content = models.TextField()
  327. and you want to do some custom validation for ``headline``, while keeping
  328. the ``blank`` and ``help_text`` values as specified, you might define
  329. ``ArticleForm`` like this::
  330. class ArticleForm(ModelForm):
  331. headline = MyFormField(max_length=200, required=False,
  332. help_text="Use puns liberally")
  333. class Meta:
  334. model = Article
  335. fields = ['headline', 'content']
  336. You must ensure that the type of the form field can be used to set the
  337. contents of the corresponding model field. When they are not compatible,
  338. you will get a ``ValueError`` as no implicit conversion takes place.
  339. See the :doc:`form field documentation </ref/forms/fields>` for more information
  340. on fields and their arguments.
  341. Enabling localization of fields
  342. -------------------------------
  343. .. versionadded:: 1.6
  344. By default, the fields in a ``ModelForm`` will not localize their data. To
  345. enable localization for fields, you can use the ``localized_fields``
  346. attribute on the ``Meta`` class.
  347. >>> class AuthorForm(ModelForm):
  348. ... class Meta:
  349. ... model = Author
  350. ... localized_fields = ('birth_date',)
  351. If ``localized_fields`` is set to the special value ``'__all__'``, all fields
  352. will be localized.
  353. .. _overriding-modelform-clean-method:
  354. Overriding the clean() method
  355. -----------------------------
  356. You can override the ``clean()`` method on a model form to provide additional
  357. validation in the same way you can on a normal form.
  358. In this regard, model forms have two specific characteristics when compared to
  359. forms:
  360. By default the ``clean()`` method validates the uniqueness of fields that are
  361. marked as ``unique``, ``unique_together`` or ``unique_for_date|month|year`` on
  362. the model. Therefore, if you would like to override the ``clean()`` method and
  363. maintain the default validation, you must call the parent class's ``clean()``
  364. method.
  365. Also, a model form instance bound to a model object will contain a
  366. ``self.instance`` attribute that gives model form methods access to that
  367. specific model instance.
  368. Form inheritance
  369. ----------------
  370. As with basic forms, you can extend and reuse ``ModelForms`` by inheriting
  371. them. This is useful if you need to declare extra fields or extra methods on a
  372. parent class for use in a number of forms derived from models. For example,
  373. using the previous ``ArticleForm`` class::
  374. >>> class EnhancedArticleForm(ArticleForm):
  375. ... def clean_pub_date(self):
  376. ... ...
  377. This creates a form that behaves identically to ``ArticleForm``, except there's
  378. some extra validation and cleaning for the ``pub_date`` field.
  379. You can also subclass the parent's ``Meta`` inner class if you want to change
  380. the ``Meta.fields`` or ``Meta.excludes`` lists::
  381. >>> class RestrictedArticleForm(EnhancedArticleForm):
  382. ... class Meta(ArticleForm.Meta):
  383. ... exclude = ('body',)
  384. This adds the extra method from the ``EnhancedArticleForm`` and modifies
  385. the original ``ArticleForm.Meta`` to remove one field.
  386. There are a couple of things to note, however.
  387. * Normal Python name resolution rules apply. If you have multiple base
  388. classes that declare a ``Meta`` inner class, only the first one will be
  389. used. This means the child's ``Meta``, if it exists, otherwise the
  390. ``Meta`` of the first parent, etc.
  391. * For technical reasons, a subclass cannot inherit from both a ``ModelForm``
  392. and a ``Form`` simultaneously.
  393. Chances are these notes won't affect you unless you're trying to do something
  394. tricky with subclassing.
  395. Interaction with model validation
  396. ---------------------------------
  397. As part of its validation process, ``ModelForm`` will call the ``clean()``
  398. method of each field on your model that has a corresponding field on your form.
  399. If you have excluded any model fields, validation will not be run on those
  400. fields. See the :doc:`form validation </ref/forms/validation>` documentation
  401. for more on how field cleaning and validation work. Also, your model's
  402. ``clean()`` method will be called before any uniqueness checks are made. See
  403. :ref:`Validating objects <validating-objects>` for more information on the
  404. model's ``clean()`` hook.
  405. .. _modelforms-factory:
  406. ModelForm factory function
  407. --------------------------
  408. You can create forms from a given model using the standalone function
  409. :func:`~django.forms.models.modelform_factory`, instead of using a class
  410. definition. This may be more convenient if you do not have many customizations
  411. to make::
  412. >>> from django.forms.models import modelform_factory
  413. >>> BookForm = modelform_factory(Book, fields=("author", "title"))
  414. This can also be used to make simple modifications to existing forms, for
  415. example by specifying the widgets to be used for a given field::
  416. >>> from django.forms import Textarea
  417. >>> Form = modelform_factory(Book, form=BookForm,
  418. widgets={"title": Textarea()})
  419. The fields to include can be specified using the ``fields`` and ``exclude``
  420. keyword arguments, or the corresponding attributes on the ``ModelForm`` inner
  421. ``Meta`` class. Please see the ``ModelForm`` :ref:`modelforms-selecting-fields`
  422. documentation.
  423. ... or enable localization for specific fields::
  424. >>> Form = modelform_factory(Author, form=AuthorForm, localized_fields=("birth_date",))
  425. .. _model-formsets:
  426. Model formsets
  427. ==============
  428. .. class:: models.BaseModelFormSet
  429. Like :doc:`regular formsets </topics/forms/formsets>`, Django provides a couple
  430. of enhanced formset classes that make it easy to work with Django models. Let's
  431. reuse the ``Author`` model from above::
  432. >>> from django.forms.models import modelformset_factory
  433. >>> AuthorFormSet = modelformset_factory(Author)
  434. This will create a formset that is capable of working with the data associated
  435. with the ``Author`` model. It works just like a regular formset::
  436. >>> formset = AuthorFormSet()
  437. >>> print(formset)
  438. <input type="hidden" name="form-TOTAL_FORMS" value="1" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" />
  439. <tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /></td></tr>
  440. <tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title">
  441. <option value="" selected="selected">---------</option>
  442. <option value="MR">Mr.</option>
  443. <option value="MRS">Mrs.</option>
  444. <option value="MS">Ms.</option>
  445. </select></td></tr>
  446. <tr><th><label for="id_form-0-birth_date">Birth date:</label></th><td><input type="text" name="form-0-birth_date" id="id_form-0-birth_date" /><input type="hidden" name="form-0-id" id="id_form-0-id" /></td></tr>
  447. .. note::
  448. :func:`~django.forms.models.modelformset_factory` uses
  449. :func:`~django.forms.formsets.formset_factory` to generate formsets. This
  450. means that a model formset is just an extension of a basic formset that
  451. knows how to interact with a particular model.
  452. Changing the queryset
  453. ---------------------
  454. By default, when you create a formset from a model, the formset will use a
  455. queryset that includes all objects in the model (e.g.,
  456. ``Author.objects.all()``). You can override this behavior by using the
  457. ``queryset`` argument::
  458. >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  459. Alternatively, you can create a subclass that sets ``self.queryset`` in
  460. ``__init__``::
  461. from django.forms.models import BaseModelFormSet
  462. class BaseAuthorFormSet(BaseModelFormSet):
  463. def __init__(self, *args, **kwargs):
  464. super(BaseAuthorFormSet, self).__init__(*args, **kwargs)
  465. self.queryset = Author.objects.filter(name__startswith='O')
  466. Then, pass your ``BaseAuthorFormSet`` class to the factory function::
  467. >>> AuthorFormSet = modelformset_factory(Author, formset=BaseAuthorFormSet)
  468. If you want to return a formset that doesn't include *any* pre-existing
  469. instances of the model, you can specify an empty QuerySet::
  470. >>> AuthorFormSet(queryset=Author.objects.none())
  471. Controlling which fields are used with ``fields`` and ``exclude``
  472. -----------------------------------------------------------------
  473. By default, a model formset uses all fields in the model that are not marked
  474. with ``editable=False``. However, this can be overridden at the formset level::
  475. >>> AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))
  476. Using ``fields`` restricts the formset to use only the given fields.
  477. Alternatively, you can take an "opt-out" approach, specifying which fields to
  478. exclude::
  479. >>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',))
  480. Specifying widgets to use in the form with ``widgets``
  481. ------------------------------------------------------
  482. .. versionadded:: 1.6
  483. Using the ``widgets`` parameter, you can specify a dictionary of values to
  484. customize the ``ModelForm``'s widget class for a particular field. This
  485. works the same way as the ``widgets`` dictionary on the inner ``Meta``
  486. class of a ``ModelForm`` works::
  487. >>> AuthorFormSet = modelformset_factory(
  488. ... Author, widgets={'name': Textarea(attrs={'cols': 80, 'rows': 20})
  489. Enabling localization for fields with ``localized_fields``
  490. ----------------------------------------------------------
  491. .. versionadded:: 1.6
  492. Using the ``localized_fields`` parameter, you can enable localization for
  493. fields in the form.
  494. >>> AuthorFormSet = modelformset_factory(
  495. ... Author, localized_fields=('value',))
  496. If ``localized_fields`` is set to the special value ``'__all__'``, all fields
  497. will be localized.
  498. Providing initial values
  499. ------------------------
  500. As with regular formsets, it's possible to :ref:`specify initial data
  501. <formsets-initial-data>` for forms in the formset by specifying an ``initial``
  502. parameter when instantiating the model formset class returned by
  503. :func:`~django.forms.models.modelformset_factory`. However, with model
  504. formsets, the initial values only apply to extra forms, those that aren't bound
  505. to an existing object instance.
  506. .. _saving-objects-in-the-formset:
  507. Saving objects in the formset
  508. -----------------------------
  509. As with a ``ModelForm``, you can save the data as a model object. This is done
  510. with the formset's ``save()`` method::
  511. # Create a formset instance with POST data.
  512. >>> formset = AuthorFormSet(request.POST)
  513. # Assuming all is valid, save the data.
  514. >>> instances = formset.save()
  515. The ``save()`` method returns the instances that have been saved to the
  516. database. If a given instance's data didn't change in the bound data, the
  517. instance won't be saved to the database and won't be included in the return
  518. value (``instances``, in the above example).
  519. When fields are missing from the form (for example because they have been
  520. excluded), these fields will not be set by the ``save()`` method. You can find
  521. more information about this restriction, which also holds for regular
  522. ``ModelForms``, in `Selecting the fields to use`_.
  523. Pass ``commit=False`` to return the unsaved model instances::
  524. # don't save to the database
  525. >>> instances = formset.save(commit=False)
  526. >>> for instance in instances:
  527. ... # do something with instance
  528. ... instance.save()
  529. This gives you the ability to attach data to the instances before saving them
  530. to the database. If your formset contains a ``ManyToManyField``, you'll also
  531. need to call ``formset.save_m2m()`` to ensure the many-to-many relationships
  532. are saved properly.
  533. .. _model-formsets-max-num:
  534. Limiting the number of editable objects
  535. ---------------------------------------
  536. As with regular formsets, you can use the ``max_num`` and ``extra`` parameters
  537. to :func:`~django.forms.models.modelformset_factory` to limit the number of
  538. extra forms displayed.
  539. ``max_num`` does not prevent existing objects from being displayed::
  540. >>> Author.objects.order_by('name')
  541. [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]
  542. >>> AuthorFormSet = modelformset_factory(Author, max_num=1)
  543. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  544. >>> [x.name for x in formset.get_queryset()]
  545. [u'Charles Baudelaire', u'Paul Verlaine', u'Walt Whitman']
  546. If the value of ``max_num`` is greater than the number of existing related
  547. objects, up to ``extra`` additional blank forms will be added to the formset,
  548. so long as the total number of forms does not exceed ``max_num``::
  549. >>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2)
  550. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  551. >>> for form in formset:
  552. ... print(form.as_table())
  553. <tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" value="Charles Baudelaire" maxlength="100" /><input type="hidden" name="form-0-id" value="1" id="id_form-0-id" /></td></tr>
  554. <tr><th><label for="id_form-1-name">Name:</label></th><td><input id="id_form-1-name" type="text" name="form-1-name" value="Paul Verlaine" maxlength="100" /><input type="hidden" name="form-1-id" value="3" id="id_form-1-id" /></td></tr>
  555. <tr><th><label for="id_form-2-name">Name:</label></th><td><input id="id_form-2-name" type="text" name="form-2-name" value="Walt Whitman" maxlength="100" /><input type="hidden" name="form-2-id" value="2" id="id_form-2-id" /></td></tr>
  556. <tr><th><label for="id_form-3-name">Name:</label></th><td><input id="id_form-3-name" type="text" name="form-3-name" maxlength="100" /><input type="hidden" name="form-3-id" id="id_form-3-id" /></td></tr>
  557. A ``max_num`` value of ``None`` (the default) puts a high limit on the number
  558. of forms displayed (1000). In practice this is equivalent to no limit.
  559. Using a model formset in a view
  560. -------------------------------
  561. Model formsets are very similar to formsets. Let's say we want to present a
  562. formset to edit ``Author`` model instances::
  563. def manage_authors(request):
  564. AuthorFormSet = modelformset_factory(Author)
  565. if request.method == 'POST':
  566. formset = AuthorFormSet(request.POST, request.FILES)
  567. if formset.is_valid():
  568. formset.save()
  569. # do something.
  570. else:
  571. formset = AuthorFormSet()
  572. return render_to_response("manage_authors.html", {
  573. "formset": formset,
  574. })
  575. As you can see, the view logic of a model formset isn't drastically different
  576. than that of a "normal" formset. The only difference is that we call
  577. ``formset.save()`` to save the data into the database. (This was described
  578. above, in :ref:`saving-objects-in-the-formset`.)
  579. Overiding ``clean()`` on a ``model_formset``
  580. --------------------------------------------
  581. Just like with ``ModelForms``, by default the ``clean()`` method of a
  582. ``model_formset`` will validate that none of the items in the formset violate
  583. the unique constraints on your model (either ``unique``, ``unique_together`` or
  584. ``unique_for_date|month|year``). If you want to override the ``clean()`` method
  585. on a ``model_formset`` and maintain this validation, you must call the parent
  586. class's ``clean`` method::
  587. class MyModelFormSet(BaseModelFormSet):
  588. def clean(self):
  589. super(MyModelFormSet, self).clean()
  590. # example custom validation across forms in the formset:
  591. for form in self.forms:
  592. # your custom formset validation
  593. Using a custom queryset
  594. -----------------------
  595. As stated earlier, you can override the default queryset used by the model
  596. formset::
  597. def manage_authors(request):
  598. AuthorFormSet = modelformset_factory(Author)
  599. if request.method == "POST":
  600. formset = AuthorFormSet(request.POST, request.FILES,
  601. queryset=Author.objects.filter(name__startswith='O'))
  602. if formset.is_valid():
  603. formset.save()
  604. # Do something.
  605. else:
  606. formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  607. return render_to_response("manage_authors.html", {
  608. "formset": formset,
  609. })
  610. Note that we pass the ``queryset`` argument in both the ``POST`` and ``GET``
  611. cases in this example.
  612. Using the formset in the template
  613. ---------------------------------
  614. .. highlight:: html+django
  615. There are three ways to render a formset in a Django template.
  616. First, you can let the formset do most of the work::
  617. <form method="post" action="">
  618. {{ formset }}
  619. </form>
  620. Second, you can manually render the formset, but let the form deal with
  621. itself::
  622. <form method="post" action="">
  623. {{ formset.management_form }}
  624. {% for form in formset %}
  625. {{ form }}
  626. {% endfor %}
  627. </form>
  628. When you manually render the forms yourself, be sure to render the management
  629. form as shown above. See the :ref:`management form documentation
  630. <understanding-the-managementform>`.
  631. Third, you can manually render each field::
  632. <form method="post" action="">
  633. {{ formset.management_form }}
  634. {% for form in formset %}
  635. {% for field in form %}
  636. {{ field.label_tag }}: {{ field }}
  637. {% endfor %}
  638. {% endfor %}
  639. </form>
  640. If you opt to use this third method and you don't iterate over the fields with
  641. a ``{% for %}`` loop, you'll need to render the primary key field. For example,
  642. if you were rendering the ``name`` and ``age`` fields of a model::
  643. <form method="post" action="">
  644. {{ formset.management_form }}
  645. {% for form in formset %}
  646. {{ form.id }}
  647. <ul>
  648. <li>{{ form.name }}</li>
  649. <li>{{ form.age }}</li>
  650. </ul>
  651. {% endfor %}
  652. </form>
  653. Notice how we need to explicitly render ``{{ form.id }}``. This ensures that
  654. the model formset, in the ``POST`` case, will work correctly. (This example
  655. assumes a primary key named ``id``. If you've explicitly defined your own
  656. primary key that isn't called ``id``, make sure it gets rendered.)
  657. .. highlight:: python
  658. .. _inline-formsets:
  659. Inline formsets
  660. ===============
  661. Inline formsets is a small abstraction layer on top of model formsets. These
  662. simplify the case of working with related objects via a foreign key. Suppose
  663. you have these two models::
  664. class Author(models.Model):
  665. name = models.CharField(max_length=100)
  666. class Book(models.Model):
  667. author = models.ForeignKey(Author)
  668. title = models.CharField(max_length=100)
  669. If you want to create a formset that allows you to edit books belonging to
  670. a particular author, you could do this::
  671. >>> from django.forms.models import inlineformset_factory
  672. >>> BookFormSet = inlineformset_factory(Author, Book)
  673. >>> author = Author.objects.get(name=u'Mike Royko')
  674. >>> formset = BookFormSet(instance=author)
  675. .. note::
  676. :func:`~django.forms.models.inlineformset_factory` uses
  677. :func:`~django.forms.models.modelformset_factory` and marks
  678. ``can_delete=True``.
  679. .. seealso::
  680. :ref:`Manually rendered can_delete and can_order <manually-rendered-can-delete-and-can-order>`.
  681. More than one foreign key to the same model
  682. -------------------------------------------
  683. If your model contains more than one foreign key to the same model, you'll
  684. need to resolve the ambiguity manually using ``fk_name``. For example, consider
  685. the following model::
  686. class Friendship(models.Model):
  687. from_friend = models.ForeignKey(Friend)
  688. to_friend = models.ForeignKey(Friend)
  689. length_in_months = models.IntegerField()
  690. To resolve this, you can use ``fk_name`` to
  691. :func:`~django.forms.models.inlineformset_factory`::
  692. >>> FriendshipFormSet = inlineformset_factory(Friend, Friendship, fk_name="from_friend")
  693. Using an inline formset in a view
  694. ---------------------------------
  695. You may want to provide a view that allows a user to edit the related objects
  696. of a model. Here's how you can do that::
  697. def manage_books(request, author_id):
  698. author = Author.objects.get(pk=author_id)
  699. BookInlineFormSet = inlineformset_factory(Author, Book)
  700. if request.method == "POST":
  701. formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
  702. if formset.is_valid():
  703. formset.save()
  704. # Do something. Should generally end with a redirect. For example:
  705. return HttpResponseRedirect(author.get_absolute_url())
  706. else:
  707. formset = BookInlineFormSet(instance=author)
  708. return render_to_response("manage_books.html", {
  709. "formset": formset,
  710. })
  711. Notice how we pass ``instance`` in both the ``POST`` and ``GET`` cases.
  712. Specifying widgets to use in the inline form
  713. --------------------------------------------
  714. .. versionadded:: 1.6
  715. ``inlineformset_factory`` uses ``modelformset_factory`` and passes most
  716. of its arguments to ``modelformset_factory``. This means you can use
  717. the ``widgets`` parameter in much the same way as passing it to
  718. ``modelformset_factory``. See `Specifying widgets to use in the form with widgets`_ above.