modelforms.txt 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. .. _topics-forms-modelforms:
  2. ==========================
  3. Creating forms from models
  4. ==========================
  5. ``ModelForm``
  6. =============
  7. If you're building a database-driven app, chances are you'll have forms that
  8. map closely to Django models. For instance, you might have a ``BlogComment``
  9. model, and you want to create a form that lets people submit comments. In this
  10. case, it would be redundant to define the field types in your form, because
  11. you've already defined the fields in your model.
  12. For this reason, Django provides a helper class that let you create a ``Form``
  13. class from a Django model.
  14. For example::
  15. >>> from django.forms import ModelForm
  16. # Create the form class.
  17. >>> class ArticleForm(ModelForm):
  18. ... class Meta:
  19. ... model = Article
  20. # Creating a form to add an article.
  21. >>> form = ArticleForm()
  22. # Creating a form to change an existing article.
  23. >>> article = Article.objects.get(pk=1)
  24. >>> form = ArticleForm(instance=article)
  25. Field types
  26. -----------
  27. The generated ``Form`` class will have a form field for every model field. Each
  28. model field has a corresponding default form field. For example, a
  29. ``CharField`` on a model is represented as a ``CharField`` on a form. A
  30. model ``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is
  31. the full list of conversions:
  32. =============================== ========================================
  33. Model field Form field
  34. =============================== ========================================
  35. ``AutoField`` Not represented in the form
  36. ``BooleanField`` ``BooleanField``
  37. ``CharField`` ``CharField`` with ``max_length`` set to
  38. the model field's ``max_length``
  39. ``CommaSeparatedIntegerField`` ``CharField``
  40. ``DateField`` ``DateField``
  41. ``DateTimeField`` ``DateTimeField``
  42. ``DecimalField`` ``DecimalField``
  43. ``EmailField`` ``EmailField``
  44. ``FileField`` ``FileField``
  45. ``FilePathField`` ``CharField``
  46. ``FloatField`` ``FloatField``
  47. ``ForeignKey`` ``ModelChoiceField`` (see below)
  48. ``ImageField`` ``ImageField``
  49. ``IntegerField`` ``IntegerField``
  50. ``IPAddressField`` ``IPAddressField``
  51. ``ManyToManyField`` ``ModelMultipleChoiceField`` (see
  52. below)
  53. ``NullBooleanField`` ``CharField``
  54. ``PhoneNumberField`` ``USPhoneNumberField``
  55. (from ``django.contrib.localflavor.us``)
  56. ``PositiveIntegerField`` ``IntegerField``
  57. ``PositiveSmallIntegerField`` ``IntegerField``
  58. ``SlugField`` ``SlugField``
  59. ``SmallIntegerField`` ``IntegerField``
  60. ``TextField`` ``CharField`` with
  61. ``widget=forms.Textarea``
  62. ``TimeField`` ``TimeField``
  63. ``URLField`` ``URLField`` with ``verify_exists`` set
  64. to the model field's ``verify_exists``
  65. ``XMLField`` ``CharField`` with
  66. ``widget=forms.Textarea``
  67. =============================== ========================================
  68. .. versionadded:: 1.0
  69. The ``FloatField`` form field and ``DecimalField`` model and form fields
  70. are new in Django 1.0.
  71. As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field
  72. types are special cases:
  73. * ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``,
  74. which is a ``ChoiceField`` whose choices are a model ``QuerySet``.
  75. * ``ManyToManyField`` is represented by
  76. ``django.forms.ModelMultipleChoiceField``, which is a
  77. ``MultipleChoiceField`` whose choices are a model ``QuerySet``.
  78. In addition, each generated form field has attributes set as follows:
  79. * If the model field has ``blank=True``, then ``required`` is set to
  80. ``False`` on the form field. Otherwise, ``required=True``.
  81. * The form field's ``label`` is set to the ``verbose_name`` of the model
  82. field, with the first character capitalized.
  83. * The form field's ``help_text`` is set to the ``help_text`` of the model
  84. field.
  85. * If the model field has ``choices`` set, then the form field's ``widget``
  86. will be set to ``Select``, with choices coming from the model field's
  87. ``choices``. The choices will normally include the blank choice which is
  88. selected by default. If the field is required, this forces the user to
  89. make a selection. The blank choice will not be included if the model
  90. field has ``blank=False`` and an explicit ``default`` value (the
  91. ``default`` value will be initially selected instead).
  92. Finally, note that you can override the form field used for a given model
  93. field. See `Overriding the default field types`_ below.
  94. A full example
  95. --------------
  96. Consider this set of models::
  97. from django.db import models
  98. from django.forms import ModelForm
  99. TITLE_CHOICES = (
  100. ('MR', 'Mr.'),
  101. ('MRS', 'Mrs.'),
  102. ('MS', 'Ms.'),
  103. )
  104. class Author(models.Model):
  105. name = models.CharField(max_length=100)
  106. title = models.CharField(max_length=3, choices=TITLE_CHOICES)
  107. birth_date = models.DateField(blank=True, null=True)
  108. def __unicode__(self):
  109. return self.name
  110. class Book(models.Model):
  111. name = models.CharField(max_length=100)
  112. authors = models.ManyToManyField(Author)
  113. class AuthorForm(ModelForm):
  114. class Meta:
  115. model = Author
  116. class BookForm(ModelForm):
  117. class Meta:
  118. model = Book
  119. With these models, the ``ModelForm`` subclasses above would be roughly
  120. equivalent to this (the only difference being the ``save()`` method, which
  121. we'll discuss in a moment.)::
  122. class AuthorForm(forms.Form):
  123. name = forms.CharField(max_length=100)
  124. title = forms.CharField(max_length=3,
  125. widget=forms.Select(choices=TITLE_CHOICES))
  126. birth_date = forms.DateField(required=False)
  127. class BookForm(forms.Form):
  128. name = forms.CharField(max_length=100)
  129. authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
  130. The ``save()`` method
  131. ---------------------
  132. Every form produced by ``ModelForm`` also has a ``save()``
  133. method. This method creates and saves a database object from the data
  134. bound to the form. A subclass of ``ModelForm`` can accept an existing
  135. model instance as the keyword argument ``instance``; if this is
  136. supplied, ``save()`` will update that instance. If it's not supplied,
  137. ``save()`` will create a new instance of the specified model::
  138. # Create a form instance from POST data.
  139. >>> f = ArticleForm(request.POST)
  140. # Save a new Article object from the form's data.
  141. >>> new_article = f.save()
  142. # Create a form to edit an existing Article.
  143. >>> a = Article.objects.get(pk=1)
  144. >>> f = ArticleForm(instance=a)
  145. >>> f.save()
  146. # Create a form to edit an existing Article, but use
  147. # POST data to populate the form.
  148. >>> a = Article.objects.get(pk=1)
  149. >>> f = ArticleForm(request.POST, instance=a)
  150. >>> f.save()
  151. Note that ``save()`` will raise a ``ValueError`` if the data in the form
  152. doesn't validate -- i.e., ``if form.errors``.
  153. This ``save()`` method accepts an optional ``commit`` keyword argument, which
  154. accepts either ``True`` or ``False``. If you call ``save()`` with
  155. ``commit=False``, then it will return an object that hasn't yet been saved to
  156. the database. In this case, it's up to you to call ``save()`` on the resulting
  157. model instance. This is useful if you want to do custom processing on the
  158. object before saving it, or if you want to use one of the specialized
  159. :ref:`model saving options <ref-models-force-insert>`. ``commit`` is ``True``
  160. by default.
  161. Another side effect of using ``commit=False`` is seen when your model has
  162. a many-to-many relation with another model. If your model has a many-to-many
  163. relation and you specify ``commit=False`` when you save a form, Django cannot
  164. immediately save the form data for the many-to-many relation. This is because
  165. it isn't possible to save many-to-many data for an instance until the instance
  166. exists in the database.
  167. To work around this problem, every time you save a form using ``commit=False``,
  168. Django adds a ``save_m2m()`` method to your ``ModelForm`` subclass. After
  169. you've manually saved the instance produced by the form, you can invoke
  170. ``save_m2m()`` to save the many-to-many form data. For example::
  171. # Create a form instance with POST data.
  172. >>> f = AuthorForm(request.POST)
  173. # Create, but don't save the new author instance.
  174. >>> new_author = f.save(commit=False)
  175. # Modify the author in some way.
  176. >>> new_author.some_field = 'some_value'
  177. # Save the new instance.
  178. >>> new_author.save()
  179. # Now, save the many-to-many data for the form.
  180. >>> f.save_m2m()
  181. Calling ``save_m2m()`` is only required if you use ``save(commit=False)``.
  182. When you use a simple ``save()`` on a form, all data -- including
  183. many-to-many data -- is saved without the need for any additional method calls.
  184. For example::
  185. # Create a form instance with POST data.
  186. >>> a = Author()
  187. >>> f = AuthorForm(request.POST, instance=a)
  188. # Create and save the new author instance. There's no need to do anything else.
  189. >>> new_author = f.save()
  190. Other than the ``save()`` and ``save_m2m()`` methods, a ``ModelForm`` works
  191. exactly the same way as any other ``forms`` form. For example, the
  192. ``is_valid()`` method is used to check for validity, the ``is_multipart()``
  193. method is used to determine whether a form requires multipart file upload (and
  194. hence whether ``request.FILES`` must be passed to the form), etc. See
  195. :ref:`binding-uploaded-files` for more information.
  196. Using a subset of fields on the form
  197. ------------------------------------
  198. In some cases, you may not want all the model fields to appear on the generated
  199. form. There are three ways of telling ``ModelForm`` to use only a subset of the
  200. model fields:
  201. 1. Set ``editable=False`` on the model field. As a result, *any* form
  202. created from the model via ``ModelForm`` will not include that
  203. field.
  204. 2. Use the ``fields`` attribute of the ``ModelForm``'s inner ``Meta``
  205. class. This attribute, if given, should be a list of field names
  206. to include in the form.
  207. .. versionchanged:: 1.1
  208. The form will render the fields in the same order they are specified in the
  209. ``fields`` attribute.
  210. 3. Use the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta``
  211. class. This attribute, if given, should be a list of field names
  212. to exclude from the form.
  213. For example, if you want a form for the ``Author`` model (defined
  214. above) that includes only the ``name`` and ``title`` fields, you would
  215. specify ``fields`` or ``exclude`` like this::
  216. class PartialAuthorForm(ModelForm):
  217. class Meta:
  218. model = Author
  219. fields = ('name', 'title')
  220. class PartialAuthorForm(ModelForm):
  221. class Meta:
  222. model = Author
  223. exclude = ('birth_date',)
  224. Since the Author model has only 3 fields, 'name', 'title', and
  225. 'birth_date', the forms above will contain exactly the same fields.
  226. .. note::
  227. If you specify ``fields`` or ``exclude`` when creating a form with
  228. ``ModelForm``, then the fields that are not in the resulting form will not
  229. be set by the form's ``save()`` method. Django will prevent any attempt to
  230. save an incomplete model, so if the model does not allow the missing fields
  231. to be empty, and does not provide a default value for the missing fields,
  232. any attempt to ``save()`` a ``ModelForm`` with missing fields will fail.
  233. To avoid this failure, you must instantiate your model with initial values
  234. for the missing, but required fields::
  235. author = Author(title='Mr')
  236. form = PartialAuthorForm(request.POST, instance=author)
  237. form.save()
  238. Alternatively, you can use ``save(commit=False)`` and manually set
  239. any extra required fields::
  240. form = PartialAuthorForm(request.POST)
  241. author = form.save(commit=False)
  242. author.title = 'Mr'
  243. author.save()
  244. See the `section on saving forms`_ for more details on using
  245. ``save(commit=False)``.
  246. .. _section on saving forms: `The save() method`_
  247. Overriding the default field types
  248. ----------------------------------
  249. The default field types, as described in the `Field types`_ table above, are
  250. sensible defaults. If you have a ``DateField`` in your model, chances are you'd
  251. want that to be represented as a ``DateField`` in your form. But
  252. ``ModelForm`` gives you the flexibility of changing the form field type
  253. for a given model field. You do this by declaratively specifying fields like
  254. you would in a regular ``Form``. Declared fields will override the default
  255. ones generated by using the ``model`` attribute.
  256. For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
  257. field, you could do the following::
  258. >>> class ArticleForm(ModelForm):
  259. ... pub_date = MyDateFormField()
  260. ...
  261. ... class Meta:
  262. ... model = Article
  263. If you want to override a field's default widget, then specify the ``widget``
  264. parameter when declaring the form field::
  265. >>> class ArticleForm(ModelForm):
  266. ... pub_date = DateField(widget=MyDateWidget())
  267. ...
  268. ... class Meta:
  269. ... model = Article
  270. Changing the order of fields
  271. ----------------------------
  272. .. versionadded:: 1.1
  273. By default, a ``ModelForm`` will render fields in the same order that they are
  274. defined on the model, with ``ManyToManyField`` instances appearing last. If
  275. you want to change the order in which fields are rendered, you can use the
  276. ``fields`` attribute on the ``Meta`` class.
  277. The ``fields`` attribute defines the subset of model fields that will be
  278. rendered, and the order in which they will be rendered. For example given this
  279. model::
  280. class Book(models.Model):
  281. author = models.ForeignKey(Author)
  282. title = models.CharField(max_length=100)
  283. the ``author`` field would be rendered first. If we wanted the title field
  284. to be rendered first, we could specify the following ``ModelForm``::
  285. >>> class BookForm(ModelForm):
  286. ... class Meta:
  287. ... model = Book
  288. ... fields = ['title', 'author']
  289. Overriding the clean() method
  290. -----------------------------
  291. You can override the ``clean()`` method on a model form to provide additional
  292. validation in the same way you can on a normal form. However, by default the
  293. ``clean()`` method validates the uniqueness of fields that are marked as
  294. ``unique``, ``unique_together`` or ``unique_for_date|month|year`` on the model.
  295. Therefore, if you would like to override the ``clean()`` method and maintain the
  296. default validation, you must call the parent class's ``clean()`` method.
  297. Form inheritance
  298. ----------------
  299. As with basic forms, you can extend and reuse ``ModelForms`` by inheriting
  300. them. This is useful if you need to declare extra fields or extra methods on a
  301. parent class for use in a number of forms derived from models. For example,
  302. using the previous ``ArticleForm`` class::
  303. >>> class EnhancedArticleForm(ArticleForm):
  304. ... def clean_pub_date(self):
  305. ... ...
  306. This creates a form that behaves identically to ``ArticleForm``, except there's
  307. some extra validation and cleaning for the ``pub_date`` field.
  308. You can also subclass the parent's ``Meta`` inner class if you want to change
  309. the ``Meta.fields`` or ``Meta.excludes`` lists::
  310. >>> class RestrictedArticleForm(EnhancedArticleForm):
  311. ... class Meta(ArticleForm.Meta):
  312. ... exclude = ['body']
  313. This adds the extra method from the ``EnhancedArticleForm`` and modifies
  314. the original ``ArticleForm.Meta`` to remove one field.
  315. There are a couple of things to note, however.
  316. * Normal Python name resolution rules apply. If you have multiple base
  317. classes that declare a ``Meta`` inner class, only the first one will be
  318. used. This means the child's ``Meta``, if it exists, otherwise the
  319. ``Meta`` of the first parent, etc.
  320. * For technical reasons, a subclass cannot inherit from both a ``ModelForm``
  321. and a ``Form`` simultaneously.
  322. Chances are these notes won't affect you unless you're trying to do something
  323. tricky with subclassing.
  324. .. _model-formsets:
  325. Model formsets
  326. ==============
  327. Like :ref:`regular formsets <topics-forms-formsets>`, Django provides a couple
  328. of enhanced formset classes that make it easy to work with Django models. Let's
  329. reuse the ``Author`` model from above::
  330. >>> from django.forms.models import modelformset_factory
  331. >>> AuthorFormSet = modelformset_factory(Author)
  332. This will create a formset that is capable of working with the data associated
  333. with the ``Author`` model. It works just like a regular formset::
  334. >>> formset = AuthorFormSet()
  335. >>> print formset
  336. <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" />
  337. <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>
  338. <tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title">
  339. <option value="" selected="selected">---------</option>
  340. <option value="MR">Mr.</option>
  341. <option value="MRS">Mrs.</option>
  342. <option value="MS">Ms.</option>
  343. </select></td></tr>
  344. <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>
  345. .. note::
  346. ``modelformset_factory`` uses ``formset_factory`` to generate formsets.
  347. This means that a model formset is just an extension of a basic formset
  348. that knows how to interact with a particular model.
  349. Changing the queryset
  350. ---------------------
  351. By default, when you create a formset from a model, the formset will use a
  352. queryset that includes all objects in the model (e.g.,
  353. ``Author.objects.all()``). You can override this behavior by using the
  354. ``queryset`` argument::
  355. >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  356. Alternatively, you can create a subclass that sets ``self.queryset`` in
  357. ``__init__``::
  358. from django.forms.models import BaseModelFormSet
  359. class BaseAuthorFormSet(BaseModelFormSet):
  360. def __init__(self, *args, **kwargs):
  361. self.queryset = Author.objects.filter(name__startswith='O')
  362. super(BaseAuthorFormSet, self).__init__(*args, **kwargs)
  363. Then, pass your ``BaseAuthorFormSet`` class to the factory function::
  364. >>> AuthorFormSet = modelformset_factory(Author, formset=BaseAuthorFormSet)
  365. Controlling which fields are used with ``fields`` and ``exclude``
  366. -----------------------------------------------------------------
  367. By default, a model formset uses all fields in the model that are not marked
  368. with ``editable=False``. However, this can be overridden at the formset level::
  369. >>> AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))
  370. Using ``fields`` restricts the formset to use only the given fields.
  371. Alternatively, you can take an "opt-out" approach, specifying which fields to
  372. exclude::
  373. >>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',))
  374. .. _saving-objects-in-the-formset:
  375. Saving objects in the formset
  376. -----------------------------
  377. As with a ``ModelForm``, you can save the data as a model object. This is done
  378. with the formset's ``save()`` method::
  379. # Create a formset instance with POST data.
  380. >>> formset = AuthorFormSet(request.POST)
  381. # Assuming all is valid, save the data.
  382. >>> instances = formset.save()
  383. The ``save()`` method returns the instances that have been saved to the
  384. database. If a given instance's data didn't change in the bound data, the
  385. instance won't be saved to the database and won't be included in the return
  386. value (``instances``, in the above example).
  387. Pass ``commit=False`` to return the unsaved model instances::
  388. # don't save to the database
  389. >>> instances = formset.save(commit=False)
  390. >>> for instance in instances:
  391. ... # do something with instance
  392. ... instance.save()
  393. This gives you the ability to attach data to the instances before saving them
  394. to the database. If your formset contains a ``ManyToManyField``, you'll also
  395. need to call ``formset.save_m2m()`` to ensure the many-to-many relationships
  396. are saved properly.
  397. .. _model-formsets-max-num:
  398. Limiting the number of editable objects
  399. ---------------------------------------
  400. As with regular formsets, you can use the ``max_num`` parameter to
  401. ``modelformset_factory`` to limit the number of forms displayed. With
  402. model formsets, this property limits the query to select only the maximum
  403. number of objects needed::
  404. >>> Author.objects.order_by('name')
  405. [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]
  406. >>> AuthorFormSet = modelformset_factory(Author, max_num=2, extra=1)
  407. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  408. >>> formset.initial
  409. [{'id': 1, 'name': u'Charles Baudelaire'}, {'id': 3, 'name': u'Paul Verlaine'}]
  410. If the value of ``max_num`` is higher than the number of objects returned, up to
  411. ``extra`` additional blank forms will be added to the formset, so long as the
  412. total number of forms does not exceed ``max_num``::
  413. >>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2)
  414. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  415. >>> for form in formset.forms:
  416. ... print form.as_table()
  417. <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>
  418. <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>
  419. <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>
  420. <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>
  421. Using a model formset in a view
  422. -------------------------------
  423. Model formsets are very similar to formsets. Let's say we want to present a
  424. formset to edit ``Author`` model instances::
  425. def manage_authors(request):
  426. AuthorFormSet = modelformset_factory(Author)
  427. if request.method == 'POST':
  428. formset = AuthorFormSet(request.POST, request.FILES)
  429. if formset.is_valid():
  430. formset.save()
  431. # do something.
  432. else:
  433. formset = AuthorFormSet()
  434. return render_to_response("manage_authors.html", {
  435. "formset": formset,
  436. })
  437. As you can see, the view logic of a model formset isn't drastically different
  438. than that of a "normal" formset. The only difference is that we call
  439. ``formset.save()`` to save the data into the database. (This was described
  440. above, in :ref:`saving-objects-in-the-formset`.)
  441. Overiding ``clean()`` on a ``model_formset``
  442. --------------------------------------------
  443. Just like with ``ModelForms``, by default the ``clean()`` method of a
  444. ``model_formset`` will validate that none of the items in the formset violate
  445. the unique constraints on your model (either ``unique``, ``unique_together`` or
  446. ``unique_for_date|month|year``). If you want to overide the ``clean()`` method
  447. on a ``model_formset`` and maintain this validation, you must call the parent
  448. class's ``clean`` method::
  449. class MyModelFormSet(BaseModelFormSet):
  450. def clean(self):
  451. super(MyModelFormSet, self).clean()
  452. # example custom validation across forms in the formset:
  453. for form in self.forms:
  454. # your custom formset validation
  455. Using a custom queryset
  456. -----------------------
  457. As stated earlier, you can override the default queryset used by the model
  458. formset::
  459. def manage_authors(request):
  460. AuthorFormSet = modelformset_factory(Author)
  461. if request.method == "POST":
  462. formset = AuthorFormSet(request.POST, request.FILES,
  463. queryset=Author.objects.filter(name__startswith='O'))
  464. if formset.is_valid():
  465. formset.save()
  466. # Do something.
  467. else:
  468. formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  469. return render_to_response("manage_authors.html", {
  470. "formset": formset,
  471. })
  472. Note that we pass the ``queryset`` argument in both the ``POST`` and ``GET``
  473. cases in this example.
  474. Using the formset in the template
  475. ---------------------------------
  476. .. highlight:: html+django
  477. There are three ways to render a formset in a Django template.
  478. First, you can let the formset do most of the work::
  479. <form method="POST" action="">
  480. {{ formset }}
  481. </form>
  482. Second, you can manually render the formset, but let the form deal with
  483. itself::
  484. <form method="POST" action="">
  485. {{ formset.management_form }}
  486. {% for form in formset.forms %}
  487. {{ form }}
  488. {% endfor %}
  489. </form>
  490. When you manually render the forms yourself, be sure to render the management
  491. form as shown above. See the :ref:`management form documentation
  492. <understanding-the-managementform>`.
  493. Third, you can manually render each field::
  494. <form method="POST" action="">
  495. {{ formset.management_form }}
  496. {% for form in formset.forms %}
  497. {% for field in form %}
  498. {{ field.label_tag }}: {{ field }}
  499. {% endfor %}
  500. {% endfor %}
  501. </form>
  502. If you opt to use this third method and you don't iterate over the fields with
  503. a ``{% for %}`` loop, you'll need to render the primary key field. For example,
  504. if you were rendering the ``name`` and ``age`` fields of a model::
  505. <form method="POST" action="">
  506. {{ formset.management_form }}
  507. {% for form in formset.forms %}
  508. {{ form.id }}
  509. <ul>
  510. <li>{{ form.name }}</li>
  511. <li>{{ form.age }}</li>
  512. </ul>
  513. {% endfor %}
  514. </form>
  515. Notice how we need to explicitly render ``{{ form.id }}``. This ensures that
  516. the model formset, in the ``POST`` case, will work correctly. (This example
  517. assumes a primary key named ``id``. If you've explicitly defined your own
  518. primary key that isn't called ``id``, make sure it gets rendered.)
  519. .. highlight:: python
  520. Inline formsets
  521. ===============
  522. Inline formsets is a small abstraction layer on top of model formsets. These
  523. simplify the case of working with related objects via a foreign key. Suppose
  524. you have these two models::
  525. class Author(models.Model):
  526. name = models.CharField(max_length=100)
  527. class Book(models.Model):
  528. author = models.ForeignKey(Author)
  529. title = models.CharField(max_length=100)
  530. If you want to create a formset that allows you to edit books belonging to
  531. a particular author, you could do this::
  532. >>> from django.forms.models import inlineformset_factory
  533. >>> BookFormSet = inlineformset_factory(Author, Book)
  534. >>> author = Author.objects.get(name=u'Mike Royko')
  535. >>> formset = BookFormSet(instance=author)
  536. .. note::
  537. ``inlineformset_factory`` uses ``modelformset_factory`` and marks
  538. ``can_delete=True``.
  539. More than one foreign key to the same model
  540. -------------------------------------------
  541. If your model contains more than one foreign key to the same model, you'll
  542. need to resolve the ambiguity manually using ``fk_name``. For example, consider
  543. the following model::
  544. class Friendship(models.Model):
  545. from_friend = models.ForeignKey(Friend)
  546. to_friend = models.ForeignKey(Friend)
  547. length_in_months = models.IntegerField()
  548. To resolve this, you can use ``fk_name`` to ``inlineformset_factory``::
  549. >>> FriendshipFormSet = inlineformset_factory(Friend, Friendship, fk_name="from_friend")
  550. Using an inline formset in a view
  551. ---------------------------------
  552. You may want to provide a view that allows a user to edit the related objects
  553. of a model. Here's how you can do that::
  554. def manage_books(request, author_id):
  555. author = Author.objects.get(pk=author_id)
  556. BookInlineFormSet = inlineformset_factory(Author, Book)
  557. if request.method == "POST":
  558. formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
  559. if formset.is_valid():
  560. formset.save()
  561. # Do something.
  562. else:
  563. formset = BookInlineFormSet(instance=author)
  564. return render_to_response("manage_books.html", {
  565. "formset": formset,
  566. })
  567. Notice how we pass ``instance`` in both the ``POST`` and ``GET`` cases.