modelforms.txt 34 KB

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