1. ========
    
  2. Formsets
    
  3. ========
    
  4. 
    
  5. .. currentmodule:: django.forms.formsets
    
  6. 
    
  7. .. class:: BaseFormSet
    
  8. 
    
  9. A formset is a layer of abstraction to work with multiple forms on the same
    
  10. page. It can be best compared to a data grid. Let's say you have the following
    
  11. form::
    
  12. 
    
  13.     >>> from django import forms
    
  14.     >>> class ArticleForm(forms.Form):
    
  15.     ...     title = forms.CharField()
    
  16.     ...     pub_date = forms.DateField()
    
  17. 
    
  18. You might want to allow the user to create several articles at once. To create
    
  19. a formset out of an ``ArticleForm`` you would do::
    
  20. 
    
  21.     >>> from django.forms import formset_factory
    
  22.     >>> ArticleFormSet = formset_factory(ArticleForm)
    
  23. 
    
  24. You now have created a formset class named ``ArticleFormSet``.
    
  25. Instantiating the formset gives you the ability to iterate over the forms
    
  26. in the formset and display them as you would with a regular form::
    
  27. 
    
  28.     >>> formset = ArticleFormSet()
    
  29.     >>> for form in formset:
    
  30.     ...     print(form.as_table())
    
  31.     <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title"></td></tr>
    
  32.     <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></td></tr>
    
  33. 
    
  34. As you can see it only displayed one empty form. The number of empty forms
    
  35. that is displayed is controlled by the ``extra`` parameter. By default,
    
  36. :func:`~django.forms.formsets.formset_factory` defines one extra form; the
    
  37. following example will create a formset class to display two blank forms::
    
  38. 
    
  39.     >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
    
  40. 
    
  41. Iterating over a formset will render the forms in the order they were
    
  42. created. You can change this order by providing an alternate implementation for
    
  43. the ``__iter__()`` method.
    
  44. 
    
  45. Formsets can also be indexed into, which returns the corresponding form. If you
    
  46. override ``__iter__``, you will need to also override ``__getitem__`` to have
    
  47. matching behavior.
    
  48. 
    
  49. .. _formsets-initial-data:
    
  50. 
    
  51. Using initial data with a formset
    
  52. =================================
    
  53. 
    
  54. Initial data is what drives the main usability of a formset. As shown above
    
  55. you can define the number of extra forms. What this means is that you are
    
  56. telling the formset how many additional forms to show in addition to the
    
  57. number of forms it generates from the initial data. Let's take a look at an
    
  58. example::
    
  59. 
    
  60.     >>> import datetime
    
  61.     >>> from django.forms import formset_factory
    
  62.     >>> from myapp.forms import ArticleForm
    
  63.     >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
    
  64.     >>> formset = ArticleFormSet(initial=[
    
  65.     ...     {'title': 'Django is now open source',
    
  66.     ...      'pub_date': datetime.date.today(),}
    
  67.     ... ])
    
  68. 
    
  69.     >>> for form in formset:
    
  70.     ...     print(form.as_table())
    
  71.     <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Django is now open source" id="id_form-0-title"></td></tr>
    
  72.     <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-12" id="id_form-0-pub_date"></td></tr>
    
  73.     <tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" id="id_form-1-title"></td></tr>
    
  74.     <tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" id="id_form-1-pub_date"></td></tr>
    
  75.     <tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title"></td></tr>
    
  76.     <tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></td></tr>
    
  77. 
    
  78. There are now a total of three forms showing above. One for the initial data
    
  79. that was passed in and two extra forms. Also note that we are passing in a
    
  80. list of dictionaries as the initial data.
    
  81. 
    
  82. If you use an ``initial`` for displaying a formset, you should pass the same
    
  83. ``initial`` when processing that formset's submission so that the formset can
    
  84. detect which forms were changed by the user. For example, you might have
    
  85. something like: ``ArticleFormSet(request.POST, initial=[...])``.
    
  86. 
    
  87. .. seealso::
    
  88. 
    
  89.     :ref:`Creating formsets from models with model formsets <model-formsets>`.
    
  90. 
    
  91. .. _formsets-max-num:
    
  92. 
    
  93. Limiting the maximum number of forms
    
  94. ====================================
    
  95. 
    
  96. The ``max_num`` parameter to :func:`~django.forms.formsets.formset_factory`
    
  97. gives you the ability to limit the number of forms the formset will display::
    
  98. 
    
  99.     >>> from django.forms import formset_factory
    
  100.     >>> from myapp.forms import ArticleForm
    
  101.     >>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
    
  102.     >>> formset = ArticleFormSet()
    
  103.     >>> for form in formset:
    
  104.     ...     print(form.as_table())
    
  105.     <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title"></td></tr>
    
  106.     <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></td></tr>
    
  107. 
    
  108. If the value of ``max_num`` is greater than the number of existing items in the
    
  109. initial data, up to ``extra`` additional blank forms will be added to the
    
  110. formset, so long as the total number of forms does not exceed ``max_num``. For
    
  111. example, if ``extra=2`` and ``max_num=2`` and the formset is initialized with
    
  112. one ``initial`` item, a form for the initial item and one blank form will be
    
  113. displayed.
    
  114. 
    
  115. If the number of items in the initial data exceeds ``max_num``, all initial
    
  116. data forms will be displayed regardless of the value of ``max_num`` and no
    
  117. extra forms will be displayed. For example, if ``extra=3`` and ``max_num=1``
    
  118. and the formset is initialized with two initial items, two forms with the
    
  119. initial data will be displayed.
    
  120. 
    
  121. A ``max_num`` value of ``None`` (the default) puts a high limit on the number
    
  122. of forms displayed (1000). In practice this is equivalent to no limit.
    
  123. 
    
  124. By default, ``max_num`` only affects how many forms are displayed and does not
    
  125. affect validation.  If ``validate_max=True`` is passed to the
    
  126. :func:`~django.forms.formsets.formset_factory`, then ``max_num`` will affect
    
  127. validation.  See :ref:`validate_max`.
    
  128. 
    
  129. .. _formsets-absolute-max:
    
  130. 
    
  131. Limiting the maximum number of instantiated forms
    
  132. =================================================
    
  133. 
    
  134. The ``absolute_max`` parameter to :func:`.formset_factory` allows limiting the
    
  135. number of forms that can be instantiated when supplying ``POST`` data. This
    
  136. protects against memory exhaustion attacks using forged ``POST`` requests::
    
  137. 
    
  138.     >>> from django.forms.formsets import formset_factory
    
  139.     >>> from myapp.forms import ArticleForm
    
  140.     >>> ArticleFormSet = formset_factory(ArticleForm, absolute_max=1500)
    
  141.     >>> data = {
    
  142.     ...     'form-TOTAL_FORMS': '1501',
    
  143.     ...     'form-INITIAL_FORMS': '0',
    
  144.     ... }
    
  145.     >>> formset = ArticleFormSet(data)
    
  146.     >>> len(formset.forms)
    
  147.     1500
    
  148.     >>> formset.is_valid()
    
  149.     False
    
  150.     >>> formset.non_form_errors()
    
  151.     ['Please submit at most 1000 forms.']
    
  152. 
    
  153. When ``absolute_max`` is ``None``, it defaults to ``max_num + 1000``. (If
    
  154. ``max_num`` is ``None``, it defaults to ``2000``).
    
  155. 
    
  156. If ``absolute_max`` is less than ``max_num``, a ``ValueError`` will be raised.
    
  157. 
    
  158. Formset validation
    
  159. ==================
    
  160. 
    
  161. Validation with a formset is almost identical to a regular ``Form``. There is
    
  162. an ``is_valid`` method on the formset to provide a convenient way to validate
    
  163. all forms in the formset::
    
  164. 
    
  165.     >>> from django.forms import formset_factory
    
  166.     >>> from myapp.forms import ArticleForm
    
  167.     >>> ArticleFormSet = formset_factory(ArticleForm)
    
  168.     >>> data = {
    
  169.     ...     'form-TOTAL_FORMS': '1',
    
  170.     ...     'form-INITIAL_FORMS': '0',
    
  171.     ... }
    
  172.     >>> formset = ArticleFormSet(data)
    
  173.     >>> formset.is_valid()
    
  174.     True
    
  175. 
    
  176. We passed in no data to the formset which is resulting in a valid form. The
    
  177. formset is smart enough to ignore extra forms that were not changed. If we
    
  178. provide an invalid article::
    
  179. 
    
  180.     >>> data = {
    
  181.     ...     'form-TOTAL_FORMS': '2',
    
  182.     ...     'form-INITIAL_FORMS': '0',
    
  183.     ...     'form-0-title': 'Test',
    
  184.     ...     'form-0-pub_date': '1904-06-16',
    
  185.     ...     'form-1-title': 'Test',
    
  186.     ...     'form-1-pub_date': '', # <-- this date is missing but required
    
  187.     ... }
    
  188.     >>> formset = ArticleFormSet(data)
    
  189.     >>> formset.is_valid()
    
  190.     False
    
  191.     >>> formset.errors
    
  192.     [{}, {'pub_date': ['This field is required.']}]
    
  193. 
    
  194. As we can see, ``formset.errors`` is a list whose entries correspond to the
    
  195. forms in the formset. Validation was performed for each of the two forms, and
    
  196. the expected error message appears for the second item.
    
  197. 
    
  198. Just like when using a normal ``Form``, each field in a formset's forms may
    
  199. include HTML attributes such as ``maxlength`` for browser validation. However,
    
  200. form fields of formsets won't include the ``required`` attribute as that
    
  201. validation may be incorrect when adding and deleting forms.
    
  202. 
    
  203. .. method:: BaseFormSet.total_error_count()
    
  204. 
    
  205. To check how many errors there are in the formset, we can use the
    
  206. ``total_error_count`` method::
    
  207. 
    
  208.     >>> # Using the previous example
    
  209.     >>> formset.errors
    
  210.     [{}, {'pub_date': ['This field is required.']}]
    
  211.     >>> len(formset.errors)
    
  212.     2
    
  213.     >>> formset.total_error_count()
    
  214.     1
    
  215. 
    
  216. We can also check if form data differs from the initial data (i.e. the form was
    
  217. sent without any data)::
    
  218. 
    
  219.     >>> data = {
    
  220.     ...     'form-TOTAL_FORMS': '1',
    
  221.     ...     'form-INITIAL_FORMS': '0',
    
  222.     ...     'form-0-title': '',
    
  223.     ...     'form-0-pub_date': '',
    
  224.     ... }
    
  225.     >>> formset = ArticleFormSet(data)
    
  226.     >>> formset.has_changed()
    
  227.     False
    
  228. 
    
  229. .. _understanding-the-managementform:
    
  230. 
    
  231. Understanding the ``ManagementForm``
    
  232. ------------------------------------
    
  233. 
    
  234. You may have noticed the additional data (``form-TOTAL_FORMS``,
    
  235. ``form-INITIAL_FORMS``) that was required in the formset's data above. This
    
  236. data is required for the ``ManagementForm``. This form is used by the formset
    
  237. to manage the collection of forms contained in the formset. If you don't
    
  238. provide this management data, the formset will be invalid::
    
  239. 
    
  240.     >>> data = {
    
  241.     ...     'form-0-title': 'Test',
    
  242.     ...     'form-0-pub_date': '',
    
  243.     ... }
    
  244.     >>> formset = ArticleFormSet(data)
    
  245.     >>> formset.is_valid()
    
  246.     False
    
  247. 
    
  248. It is used to keep track of how many form instances are being displayed. If
    
  249. you are adding new forms via JavaScript, you should increment the count fields
    
  250. in this form as well. On the other hand, if you are using JavaScript to allow
    
  251. deletion of existing objects, then you need to ensure the ones being removed
    
  252. are properly marked for deletion by including ``form-#-DELETE`` in the ``POST``
    
  253. data. It is expected that all forms are present in the ``POST`` data regardless.
    
  254. 
    
  255. The management form is available as an attribute of the formset
    
  256. itself. When rendering a formset in a template, you can include all
    
  257. the management data by rendering ``{{ my_formset.management_form }}``
    
  258. (substituting the name of your formset as appropriate).
    
  259. 
    
  260. .. note::
    
  261. 
    
  262.     As well as the ``form-TOTAL_FORMS`` and ``form-INITIAL_FORMS`` fields shown
    
  263.     in the examples here, the management form also includes
    
  264.     ``form-MIN_NUM_FORMS`` and ``form-MAX_NUM_FORMS`` fields. They are output
    
  265.     with the rest of the management form, but only for the convenience of
    
  266.     client-side code. These fields are not required and so are not shown in
    
  267.     the example ``POST`` data.
    
  268. 
    
  269. ``total_form_count`` and ``initial_form_count``
    
  270. -----------------------------------------------
    
  271. 
    
  272. ``BaseFormSet`` has a couple of methods that are closely related to the
    
  273. ``ManagementForm``, ``total_form_count`` and ``initial_form_count``.
    
  274. 
    
  275. ``total_form_count`` returns the total number of forms in this formset.
    
  276. ``initial_form_count`` returns the number of forms in the formset that were
    
  277. pre-filled, and is also used to determine how many forms are required. You
    
  278. will probably never need to override either of these methods, so please be
    
  279. sure you understand what they do before doing so.
    
  280. 
    
  281. .. _empty_form:
    
  282. 
    
  283. ``empty_form``
    
  284. --------------
    
  285. 
    
  286. ``BaseFormSet`` provides an additional attribute ``empty_form`` which returns
    
  287. a form instance with a prefix of ``__prefix__`` for easier use in dynamic
    
  288. forms with JavaScript.
    
  289. 
    
  290. .. _formsets-error-messages:
    
  291. 
    
  292. ``error_messages``
    
  293. ------------------
    
  294. 
    
  295. The ``error_messages`` argument lets you override the default messages that the
    
  296. formset will raise. Pass in a dictionary with keys matching the error messages
    
  297. you want to override. Error message keys include ``'too_few_forms'``,
    
  298. ``'too_many_forms'``, and ``'missing_management_form'``. The
    
  299. ``'too_few_forms'`` and ``'too_many_forms'`` error messages may contain
    
  300. ``%(num)d``, which will be replaced with ``min_num`` and ``max_num``,
    
  301. respectively.
    
  302. 
    
  303. For example, here is the default error message when the
    
  304. management form is missing::
    
  305. 
    
  306.     >>> formset = ArticleFormSet({})
    
  307.     >>> formset.is_valid()
    
  308.     False
    
  309.     >>> formset.non_form_errors()
    
  310.     ['ManagementForm data is missing or has been tampered with. Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. You may need to file a bug report if the issue persists.']
    
  311. 
    
  312. And here is a custom error message::
    
  313. 
    
  314.     >>> formset = ArticleFormSet({}, error_messages={'missing_management_form': 'Sorry, something went wrong.'})
    
  315.     >>> formset.is_valid()
    
  316.     False
    
  317.     >>> formset.non_form_errors()
    
  318.     ['Sorry, something went wrong.']
    
  319. 
    
  320. .. versionchanged:: 4.1
    
  321. 
    
  322.     The ``'too_few_forms'`` and ``'too_many_forms'`` keys were added.
    
  323. 
    
  324. Custom formset validation
    
  325. -------------------------
    
  326. 
    
  327. A formset has a ``clean`` method similar to the one on a ``Form`` class. This
    
  328. is where you define your own validation that works at the formset level::
    
  329. 
    
  330.     >>> from django.core.exceptions import ValidationError
    
  331.     >>> from django.forms import BaseFormSet
    
  332.     >>> from django.forms import formset_factory
    
  333.     >>> from myapp.forms import ArticleForm
    
  334. 
    
  335.     >>> class BaseArticleFormSet(BaseFormSet):
    
  336.     ...     def clean(self):
    
  337.     ...         """Checks that no two articles have the same title."""
    
  338.     ...         if any(self.errors):
    
  339.     ...             # Don't bother validating the formset unless each form is valid on its own
    
  340.     ...             return
    
  341.     ...         titles = []
    
  342.     ...         for form in self.forms:
    
  343.     ...             if self.can_delete and self._should_delete_form(form):
    
  344.     ...                 continue
    
  345.     ...             title = form.cleaned_data.get('title')
    
  346.     ...             if title in titles:
    
  347.     ...                 raise ValidationError("Articles in a set must have distinct titles.")
    
  348.     ...             titles.append(title)
    
  349. 
    
  350.     >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
    
  351.     >>> data = {
    
  352.     ...     'form-TOTAL_FORMS': '2',
    
  353.     ...     'form-INITIAL_FORMS': '0',
    
  354.     ...     'form-0-title': 'Test',
    
  355.     ...     'form-0-pub_date': '1904-06-16',
    
  356.     ...     'form-1-title': 'Test',
    
  357.     ...     'form-1-pub_date': '1912-06-23',
    
  358.     ... }
    
  359.     >>> formset = ArticleFormSet(data)
    
  360.     >>> formset.is_valid()
    
  361.     False
    
  362.     >>> formset.errors
    
  363.     [{}, {}]
    
  364.     >>> formset.non_form_errors()
    
  365.     ['Articles in a set must have distinct titles.']
    
  366. 
    
  367. The formset ``clean`` method is called after all the ``Form.clean`` methods
    
  368. have been called. The errors will be found using the ``non_form_errors()``
    
  369. method on the formset.
    
  370. 
    
  371. Non-form errors will be rendered with an additional class of ``nonform`` to
    
  372. help distinguish them from form-specific errors. For example,
    
  373. ``{{ formset.non_form_errors }}`` would look like:
    
  374. 
    
  375. .. code-block:: html+django
    
  376. 
    
  377.     <ul class="errorlist nonform">
    
  378.         <li>Articles in a set must have distinct titles.</li>
    
  379.     </ul>
    
  380. 
    
  381. .. versionchanged:: 4.0
    
  382. 
    
  383.     The additional ``nonform`` class was added.
    
  384. 
    
  385. Validating the number of forms in a formset
    
  386. ===========================================
    
  387. 
    
  388. Django provides a couple ways to validate the minimum or maximum number of
    
  389. submitted forms. Applications which need more customizable validation of the
    
  390. number of forms should use custom formset validation.
    
  391. 
    
  392. .. _validate_max:
    
  393. 
    
  394. ``validate_max``
    
  395. ----------------
    
  396. 
    
  397. If ``validate_max=True`` is passed to
    
  398. :func:`~django.forms.formsets.formset_factory`, validation will also check
    
  399. that the number of forms in the data set, minus those marked for
    
  400. deletion, is less than or equal to ``max_num``.
    
  401. 
    
  402.     >>> from django.forms import formset_factory
    
  403.     >>> from myapp.forms import ArticleForm
    
  404.     >>> ArticleFormSet = formset_factory(ArticleForm, max_num=1, validate_max=True)
    
  405.     >>> data = {
    
  406.     ...     'form-TOTAL_FORMS': '2',
    
  407.     ...     'form-INITIAL_FORMS': '0',
    
  408.     ...     'form-0-title': 'Test',
    
  409.     ...     'form-0-pub_date': '1904-06-16',
    
  410.     ...     'form-1-title': 'Test 2',
    
  411.     ...     'form-1-pub_date': '1912-06-23',
    
  412.     ... }
    
  413.     >>> formset = ArticleFormSet(data)
    
  414.     >>> formset.is_valid()
    
  415.     False
    
  416.     >>> formset.errors
    
  417.     [{}, {}]
    
  418.     >>> formset.non_form_errors()
    
  419.     ['Please submit at most 1 form.']
    
  420. 
    
  421. ``validate_max=True`` validates against ``max_num`` strictly even if
    
  422. ``max_num`` was exceeded because the amount of initial data supplied was
    
  423. excessive.
    
  424. 
    
  425. The error message can be customized by passing the ``'too_many_forms'`` message
    
  426. to the :ref:`formsets-error-messages` argument.
    
  427. 
    
  428. .. note::
    
  429. 
    
  430.     Regardless of ``validate_max``, if the number of forms in a data set
    
  431.     exceeds ``absolute_max``, then the form will fail to validate as if
    
  432.     ``validate_max`` were set, and additionally only the first ``absolute_max``
    
  433.     forms will be validated. The remainder will be truncated entirely. This is
    
  434.     to protect against memory exhaustion attacks using forged POST requests.
    
  435.     See :ref:`formsets-absolute-max`.
    
  436. 
    
  437. ``validate_min``
    
  438. ----------------
    
  439. 
    
  440. If ``validate_min=True`` is passed to
    
  441. :func:`~django.forms.formsets.formset_factory`, validation will also check
    
  442. that the number of forms in the data set, minus those marked for
    
  443. deletion, is greater than or equal to ``min_num``.
    
  444. 
    
  445.     >>> from django.forms import formset_factory
    
  446.     >>> from myapp.forms import ArticleForm
    
  447.     >>> ArticleFormSet = formset_factory(ArticleForm, min_num=3, validate_min=True)
    
  448.     >>> data = {
    
  449.     ...     'form-TOTAL_FORMS': '2',
    
  450.     ...     'form-INITIAL_FORMS': '0',
    
  451.     ...     'form-0-title': 'Test',
    
  452.     ...     'form-0-pub_date': '1904-06-16',
    
  453.     ...     'form-1-title': 'Test 2',
    
  454.     ...     'form-1-pub_date': '1912-06-23',
    
  455.     ... }
    
  456.     >>> formset = ArticleFormSet(data)
    
  457.     >>> formset.is_valid()
    
  458.     False
    
  459.     >>> formset.errors
    
  460.     [{}, {}]
    
  461.     >>> formset.non_form_errors()
    
  462.     ['Please submit at least 3 forms.']
    
  463. 
    
  464. The error message can be customized by passing the ``'too_few_forms'`` message
    
  465. to the :ref:`formsets-error-messages` argument.
    
  466. 
    
  467. .. note::
    
  468. 
    
  469.     Regardless of ``validate_min``, if a formset contains no data, then
    
  470.     ``extra + min_num`` empty forms will be displayed.
    
  471. 
    
  472. Dealing with ordering and deletion of forms
    
  473. ===========================================
    
  474. 
    
  475. The :func:`~django.forms.formsets.formset_factory` provides two optional
    
  476. parameters ``can_order`` and ``can_delete`` to help with ordering of forms in
    
  477. formsets and deletion of forms from a formset.
    
  478. 
    
  479. ``can_order``
    
  480. -------------
    
  481. 
    
  482. .. attribute:: BaseFormSet.can_order
    
  483. 
    
  484. Default: ``False``
    
  485. 
    
  486. Lets you create a formset with the ability to order::
    
  487. 
    
  488.     >>> from django.forms import formset_factory
    
  489.     >>> from myapp.forms import ArticleForm
    
  490.     >>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)
    
  491.     >>> formset = ArticleFormSet(initial=[
    
  492.     ...     {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
    
  493.     ...     {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
    
  494.     ... ])
    
  495.     >>> for form in formset:
    
  496.     ...     print(form.as_table())
    
  497.     <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title"></td></tr>
    
  498.     <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date"></td></tr>
    
  499.     <tr><th><label for="id_form-0-ORDER">Order:</label></th><td><input type="number" name="form-0-ORDER" value="1" id="id_form-0-ORDER"></td></tr>
    
  500.     <tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" value="Article #2" id="id_form-1-title"></td></tr>
    
  501.     <tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" value="2008-05-11" id="id_form-1-pub_date"></td></tr>
    
  502.     <tr><th><label for="id_form-1-ORDER">Order:</label></th><td><input type="number" name="form-1-ORDER" value="2" id="id_form-1-ORDER"></td></tr>
    
  503.     <tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title"></td></tr>
    
  504.     <tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></td></tr>
    
  505.     <tr><th><label for="id_form-2-ORDER">Order:</label></th><td><input type="number" name="form-2-ORDER" id="id_form-2-ORDER"></td></tr>
    
  506. 
    
  507. This adds an additional field to each form. This new field is named ``ORDER``
    
  508. and is an ``forms.IntegerField``. For the forms that came from the initial
    
  509. data it automatically assigned them a numeric value. Let's look at what will
    
  510. happen when the user changes these values::
    
  511. 
    
  512.     >>> data = {
    
  513.     ...     'form-TOTAL_FORMS': '3',
    
  514.     ...     'form-INITIAL_FORMS': '2',
    
  515.     ...     'form-0-title': 'Article #1',
    
  516.     ...     'form-0-pub_date': '2008-05-10',
    
  517.     ...     'form-0-ORDER': '2',
    
  518.     ...     'form-1-title': 'Article #2',
    
  519.     ...     'form-1-pub_date': '2008-05-11',
    
  520.     ...     'form-1-ORDER': '1',
    
  521.     ...     'form-2-title': 'Article #3',
    
  522.     ...     'form-2-pub_date': '2008-05-01',
    
  523.     ...     'form-2-ORDER': '0',
    
  524.     ... }
    
  525. 
    
  526.     >>> formset = ArticleFormSet(data, initial=[
    
  527.     ...     {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
    
  528.     ...     {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
    
  529.     ... ])
    
  530.     >>> formset.is_valid()
    
  531.     True
    
  532.     >>> for form in formset.ordered_forms:
    
  533.     ...     print(form.cleaned_data)
    
  534.     {'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': 'Article #3'}
    
  535.     {'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': 'Article #2'}
    
  536.     {'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': 'Article #1'}
    
  537. 
    
  538. :class:`~django.forms.formsets.BaseFormSet` also provides an
    
  539. :attr:`~django.forms.formsets.BaseFormSet.ordering_widget` attribute and
    
  540. :meth:`~django.forms.formsets.BaseFormSet.get_ordering_widget` method that
    
  541. control the widget used with
    
  542. :attr:`~django.forms.formsets.BaseFormSet.can_order`.
    
  543. 
    
  544. ``ordering_widget``
    
  545. ^^^^^^^^^^^^^^^^^^^
    
  546. 
    
  547. .. attribute:: BaseFormSet.ordering_widget
    
  548. 
    
  549. Default: :class:`~django.forms.NumberInput`
    
  550. 
    
  551. Set ``ordering_widget`` to specify the widget class to be used with
    
  552. ``can_order``::
    
  553. 
    
  554.     >>> from django.forms import BaseFormSet, formset_factory
    
  555.     >>> from myapp.forms import ArticleForm
    
  556.     >>> class BaseArticleFormSet(BaseFormSet):
    
  557.     ...     ordering_widget = HiddenInput
    
  558. 
    
  559.     >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)
    
  560. 
    
  561. ``get_ordering_widget``
    
  562. ^^^^^^^^^^^^^^^^^^^^^^^
    
  563. 
    
  564. .. method:: BaseFormSet.get_ordering_widget()
    
  565. 
    
  566. Override ``get_ordering_widget()`` if you need to provide a widget instance for
    
  567. use with ``can_order``::
    
  568. 
    
  569.     >>> from django.forms import BaseFormSet, formset_factory
    
  570.     >>> from myapp.forms import ArticleForm
    
  571.     >>> class BaseArticleFormSet(BaseFormSet):
    
  572.     ...     def get_ordering_widget(self):
    
  573.     ...         return HiddenInput(attrs={'class': 'ordering'})
    
  574. 
    
  575.     >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)
    
  576. 
    
  577. ``can_delete``
    
  578. --------------
    
  579. 
    
  580. .. attribute:: BaseFormSet.can_delete
    
  581. 
    
  582. Default: ``False``
    
  583. 
    
  584. Lets you create a formset with the ability to select forms for deletion::
    
  585. 
    
  586.     >>> from django.forms import formset_factory
    
  587.     >>> from myapp.forms import ArticleForm
    
  588.     >>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True)
    
  589.     >>> formset = ArticleFormSet(initial=[
    
  590.     ...     {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
    
  591.     ...     {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
    
  592.     ... ])
    
  593.     >>> for form in formset:
    
  594.     ...     print(form.as_table())
    
  595.     <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title"></td></tr>
    
  596.     <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date"></td></tr>
    
  597.     <tr><th><label for="id_form-0-DELETE">Delete:</label></th><td><input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE"></td></tr>
    
  598.     <tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" value="Article #2" id="id_form-1-title"></td></tr>
    
  599.     <tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" value="2008-05-11" id="id_form-1-pub_date"></td></tr>
    
  600.     <tr><th><label for="id_form-1-DELETE">Delete:</label></th><td><input type="checkbox" name="form-1-DELETE" id="id_form-1-DELETE"></td></tr>
    
  601.     <tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title"></td></tr>
    
  602.     <tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></td></tr>
    
  603.     <tr><th><label for="id_form-2-DELETE">Delete:</label></th><td><input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE"></td></tr>
    
  604. 
    
  605. Similar to ``can_order`` this adds a new field to each form named ``DELETE``
    
  606. and is a ``forms.BooleanField``. When data comes through marking any of the
    
  607. delete fields you can access them with ``deleted_forms``::
    
  608. 
    
  609.     >>> data = {
    
  610.     ...     'form-TOTAL_FORMS': '3',
    
  611.     ...     'form-INITIAL_FORMS': '2',
    
  612.     ...     'form-0-title': 'Article #1',
    
  613.     ...     'form-0-pub_date': '2008-05-10',
    
  614.     ...     'form-0-DELETE': 'on',
    
  615.     ...     'form-1-title': 'Article #2',
    
  616.     ...     'form-1-pub_date': '2008-05-11',
    
  617.     ...     'form-1-DELETE': '',
    
  618.     ...     'form-2-title': '',
    
  619.     ...     'form-2-pub_date': '',
    
  620.     ...     'form-2-DELETE': '',
    
  621.     ... }
    
  622. 
    
  623.     >>> formset = ArticleFormSet(data, initial=[
    
  624.     ...     {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
    
  625.     ...     {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
    
  626.     ... ])
    
  627.     >>> [form.cleaned_data for form in formset.deleted_forms]
    
  628.     [{'DELETE': True, 'pub_date': datetime.date(2008, 5, 10), 'title': 'Article #1'}]
    
  629. 
    
  630. If you are using a :class:`ModelFormSet<django.forms.models.BaseModelFormSet>`,
    
  631. model instances for deleted forms will be deleted when you call
    
  632. ``formset.save()``.
    
  633. 
    
  634. If you call ``formset.save(commit=False)``, objects will not be deleted
    
  635. automatically.  You'll need to call ``delete()`` on each of the
    
  636. :attr:`formset.deleted_objects
    
  637. <django.forms.models.BaseModelFormSet.deleted_objects>` to actually delete
    
  638. them::
    
  639. 
    
  640.     >>> instances = formset.save(commit=False)
    
  641.     >>> for obj in formset.deleted_objects:
    
  642.     ...     obj.delete()
    
  643. 
    
  644. On the other hand, if you are using a plain ``FormSet``, it's up to you to
    
  645. handle ``formset.deleted_forms``, perhaps in your formset's ``save()`` method,
    
  646. as there's no general notion of what it means to delete a form.
    
  647. 
    
  648. :class:`~django.forms.formsets.BaseFormSet` also provides a
    
  649. :attr:`~django.forms.formsets.BaseFormSet.deletion_widget` attribute and
    
  650. :meth:`~django.forms.formsets.BaseFormSet.get_deletion_widget` method that
    
  651. control the widget used with
    
  652. :attr:`~django.forms.formsets.BaseFormSet.can_delete`.
    
  653. 
    
  654. ``deletion_widget``
    
  655. ^^^^^^^^^^^^^^^^^^^
    
  656. 
    
  657. .. versionadded:: 4.0
    
  658. 
    
  659. .. attribute:: BaseFormSet.deletion_widget
    
  660. 
    
  661. Default: :class:`~django.forms.CheckboxInput`
    
  662. 
    
  663. Set ``deletion_widget`` to specify the widget class to be used with
    
  664. ``can_delete``::
    
  665. 
    
  666.     >>> from django.forms import BaseFormSet, formset_factory
    
  667.     >>> from myapp.forms import ArticleForm
    
  668.     >>> class BaseArticleFormSet(BaseFormSet):
    
  669.     ...     deletion_widget = HiddenInput
    
  670. 
    
  671.     >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_delete=True)
    
  672. 
    
  673. ``get_deletion_widget``
    
  674. ^^^^^^^^^^^^^^^^^^^^^^^
    
  675. 
    
  676. .. versionadded:: 4.0
    
  677. 
    
  678. .. method:: BaseFormSet.get_deletion_widget()
    
  679. 
    
  680. Override ``get_deletion_widget()`` if you need to provide a widget instance for
    
  681. use with ``can_delete``::
    
  682. 
    
  683.     >>> from django.forms import BaseFormSet, formset_factory
    
  684.     >>> from myapp.forms import ArticleForm
    
  685.     >>> class BaseArticleFormSet(BaseFormSet):
    
  686.     ...     def get_deletion_widget(self):
    
  687.     ...         return HiddenInput(attrs={'class': 'deletion'})
    
  688. 
    
  689.     >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_delete=True)
    
  690. 
    
  691. ``can_delete_extra``
    
  692. --------------------
    
  693. 
    
  694. .. attribute:: BaseFormSet.can_delete_extra
    
  695. 
    
  696. Default: ``True``
    
  697. 
    
  698. While setting ``can_delete=True``, specifying ``can_delete_extra=False`` will
    
  699. remove the option to delete extra forms.
    
  700. 
    
  701. Adding additional fields to a formset
    
  702. =====================================
    
  703. 
    
  704. If you need to add additional fields to the formset this can be easily
    
  705. accomplished. The formset base class provides an ``add_fields`` method. You
    
  706. can override this method to add your own fields or even redefine the default
    
  707. fields/attributes of the order and deletion fields::
    
  708. 
    
  709.     >>> from django.forms import BaseFormSet
    
  710.     >>> from django.forms import formset_factory
    
  711.     >>> from myapp.forms import ArticleForm
    
  712.     >>> class BaseArticleFormSet(BaseFormSet):
    
  713.     ...     def add_fields(self, form, index):
    
  714.     ...         super().add_fields(form, index)
    
  715.     ...         form.fields["my_field"] = forms.CharField()
    
  716. 
    
  717.     >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
    
  718.     >>> formset = ArticleFormSet()
    
  719.     >>> for form in formset:
    
  720.     ...     print(form.as_table())
    
  721.     <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title"></td></tr>
    
  722.     <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></td></tr>
    
  723.     <tr><th><label for="id_form-0-my_field">My field:</label></th><td><input type="text" name="form-0-my_field" id="id_form-0-my_field"></td></tr>
    
  724. 
    
  725. .. _custom-formset-form-kwargs:
    
  726. 
    
  727. Passing custom parameters to formset forms
    
  728. ==========================================
    
  729. 
    
  730. Sometimes your form class takes custom parameters, like ``MyArticleForm``.
    
  731. You can pass this parameter when instantiating the formset::
    
  732. 
    
  733.     >>> from django.forms import BaseFormSet
    
  734.     >>> from django.forms import formset_factory
    
  735.     >>> from myapp.forms import ArticleForm
    
  736. 
    
  737.     >>> class MyArticleForm(ArticleForm):
    
  738.     ...     def __init__(self, *args, user, **kwargs):
    
  739.     ...         self.user = user
    
  740.     ...         super().__init__(*args, **kwargs)
    
  741. 
    
  742.     >>> ArticleFormSet = formset_factory(MyArticleForm)
    
  743.     >>> formset = ArticleFormSet(form_kwargs={'user': request.user})
    
  744. 
    
  745. The ``form_kwargs`` may also depend on the specific form instance. The formset
    
  746. base class provides a ``get_form_kwargs`` method. The method takes a single
    
  747. argument - the index of the form in the formset. The index is ``None`` for the
    
  748. :ref:`empty_form`::
    
  749. 
    
  750.     >>> from django.forms import BaseFormSet
    
  751.     >>> from django.forms import formset_factory
    
  752. 
    
  753.     >>> class BaseArticleFormSet(BaseFormSet):
    
  754.     ...     def get_form_kwargs(self, index):
    
  755.     ...         kwargs = super().get_form_kwargs(index)
    
  756.     ...         kwargs['custom_kwarg'] = index
    
  757.     ...         return kwargs
    
  758. 
    
  759.     >>> ArticleFormSet = formset_factory(MyArticleForm, formset=BaseArticleFormSet)
    
  760.     >>> formset = ArticleFormSet()
    
  761. 
    
  762. .. _formset-prefix:
    
  763. 
    
  764. Customizing a formset's prefix
    
  765. ==============================
    
  766. 
    
  767. In the rendered HTML, formsets include a prefix on each field's name. By
    
  768. default, the prefix is ``'form'``, but it can be customized using the formset's
    
  769. ``prefix`` argument.
    
  770. 
    
  771. For example, in the default case, you might see:
    
  772. 
    
  773. .. code-block:: html
    
  774. 
    
  775.     <label for="id_form-0-title">Title:</label>
    
  776.     <input type="text" name="form-0-title" id="id_form-0-title">
    
  777. 
    
  778. But with ``ArticleFormset(prefix='article')`` that becomes:
    
  779. 
    
  780. .. code-block:: html
    
  781. 
    
  782.     <label for="id_article-0-title">Title:</label>
    
  783.     <input type="text" name="article-0-title" id="id_article-0-title">
    
  784. 
    
  785. This is useful if you want to :ref:`use more than one formset in a view
    
  786. <multiple-formsets-in-view>`.
    
  787. 
    
  788. .. _formset-rendering:
    
  789. 
    
  790. Using a formset in views and templates
    
  791. ======================================
    
  792. 
    
  793. Formsets have the following attributes and methods associated with rendering:
    
  794. 
    
  795. .. attribute:: BaseFormSet.renderer
    
  796. 
    
  797.     .. versionadded:: 4.0
    
  798. 
    
  799.     Specifies the :doc:`renderer </ref/forms/renderers>` to use for the
    
  800.     formset. Defaults to the renderer specified by the :setting:`FORM_RENDERER`
    
  801.     setting.
    
  802. 
    
  803. .. attribute:: BaseFormSet.template_name
    
  804. 
    
  805.     .. versionadded:: 4.0
    
  806. 
    
  807.     The name of the template rendered if the formset is cast into a string,
    
  808.     e.g. via ``print(formset)`` or in a template via ``{{ formset }}``.
    
  809. 
    
  810.     By default, a property returning the value of the renderer's
    
  811.     :attr:`~django.forms.renderers.BaseRenderer.formset_template_name`. You may
    
  812.     set it as a string template name in order to override that for a particular
    
  813.     formset class.
    
  814. 
    
  815.     This template will be used to render the formset's management form, and
    
  816.     then each form in the formset as per the template defined by the form's
    
  817.     :attr:`~django.forms.Form.template_name`.
    
  818. 
    
  819.     .. versionchanged:: 4.1
    
  820. 
    
  821.         In older versions ``template_name`` defaulted to the string value
    
  822.         ``'django/forms/formset/default.html'``.
    
  823. 
    
  824. 
    
  825. .. attribute:: BaseFormSet.template_name_div
    
  826. 
    
  827.     .. versionadded:: 4.1
    
  828. 
    
  829.     The name of the template used when calling :meth:`.as_div`. By default this
    
  830.     is ``"django/forms/formsets/div.html"``. This template renders the
    
  831.     formset's management form and then each form in the formset as per the
    
  832.     form's :meth:`~django.forms.Form.as_div` method.
    
  833. 
    
  834. .. attribute:: BaseFormSet.template_name_p
    
  835. 
    
  836.     .. versionadded:: 4.0
    
  837. 
    
  838.     The name of the template used when calling :meth:`.as_p`. By default this
    
  839.     is ``"django/forms/formsets/p.html"``. This template renders the formset's
    
  840.     management form and then each form in the formset as per the form's
    
  841.     :meth:`~django.forms.Form.as_p` method.
    
  842. 
    
  843. .. attribute:: BaseFormSet.template_name_table
    
  844. 
    
  845.     .. versionadded:: 4.0
    
  846. 
    
  847.     The name of the template used when calling :meth:`.as_table`. By default
    
  848.     this is ``"django/forms/formsets/table.html"``. This template renders the
    
  849.     formset's management form and then each form in the formset as per the
    
  850.     form's :meth:`~django.forms.Form.as_table` method.
    
  851. 
    
  852. .. attribute:: BaseFormSet.template_name_ul
    
  853. 
    
  854.     .. versionadded:: 4.0
    
  855. 
    
  856.     The name of the template used when calling :meth:`.as_ul`. By default this
    
  857.     is ``"django/forms/formsets/ul.html"``. This template renders the formset's
    
  858.     management form and then each form in the formset as per the form's
    
  859.     :meth:`~django.forms.Form.as_ul` method.
    
  860. 
    
  861. .. method:: BaseFormSet.get_context()
    
  862. 
    
  863.     .. versionadded:: 4.0
    
  864. 
    
  865.     Returns the context for rendering a formset in a template.
    
  866. 
    
  867.     The available context is:
    
  868. 
    
  869.     * ``formset`` : The instance of the formset.
    
  870. 
    
  871. .. method:: BaseFormSet.render(template_name=None, context=None, renderer=None)
    
  872. 
    
  873.     .. versionadded:: 4.0
    
  874. 
    
  875.     The render method is called by ``__str__`` as well as the :meth:`.as_div`,
    
  876.     :meth:`.as_p`, :meth:`.as_ul`, and :meth:`.as_table` methods. All arguments
    
  877.     are optional and will default to:
    
  878. 
    
  879.     * ``template_name``: :attr:`.template_name`
    
  880.     * ``context``: Value returned by :meth:`.get_context`
    
  881.     * ``renderer``: Value returned by :attr:`.renderer`
    
  882. 
    
  883. .. method:: BaseFormSet.as_div()
    
  884. 
    
  885.     .. versionadded:: 4.1
    
  886. 
    
  887.     Renders the formset with the :attr:`.template_name_div` template.
    
  888. 
    
  889. .. method:: BaseFormSet.as_p()
    
  890. 
    
  891.     Renders the formset with the :attr:`.template_name_p` template.
    
  892. 
    
  893. .. method:: BaseFormSet.as_table()
    
  894. 
    
  895.     Renders the formset with the :attr:`.template_name_table` template.
    
  896. 
    
  897. .. method:: BaseFormSet.as_ul()
    
  898. 
    
  899.     Renders the formset with the :attr:`.template_name_ul` template.
    
  900. 
    
  901. Using a formset inside a view is not very different from using a regular
    
  902. ``Form`` class. The only thing you will want to be aware of is making sure to
    
  903. use the management form inside the template. Let's look at a sample view::
    
  904. 
    
  905.     from django.forms import formset_factory
    
  906.     from django.shortcuts import render
    
  907.     from myapp.forms import ArticleForm
    
  908. 
    
  909.     def manage_articles(request):
    
  910.         ArticleFormSet = formset_factory(ArticleForm)
    
  911.         if request.method == 'POST':
    
  912.             formset = ArticleFormSet(request.POST, request.FILES)
    
  913.             if formset.is_valid():
    
  914.                 # do something with the formset.cleaned_data
    
  915.                 pass
    
  916.         else:
    
  917.             formset = ArticleFormSet()
    
  918.         return render(request, 'manage_articles.html', {'formset': formset})
    
  919. 
    
  920. The ``manage_articles.html`` template might look like this:
    
  921. 
    
  922. .. code-block:: html+django
    
  923. 
    
  924.     <form method="post">
    
  925.         {{ formset.management_form }}
    
  926.         <table>
    
  927.             {% for form in formset %}
    
  928.             {{ form }}
    
  929.             {% endfor %}
    
  930.         </table>
    
  931.     </form>
    
  932. 
    
  933. However there's a slight shortcut for the above by letting the formset itself
    
  934. deal with the management form:
    
  935. 
    
  936. .. code-block:: html+django
    
  937. 
    
  938.     <form method="post">
    
  939.         <table>
    
  940.             {{ formset }}
    
  941.         </table>
    
  942.     </form>
    
  943. 
    
  944. The above ends up calling the :meth:`BaseFormSet.render` method on the formset
    
  945. class. This renders the formset using the template specified by the
    
  946. :attr:`~BaseFormSet.template_name` attribute. Similar to forms, by default the
    
  947. formset will be rendered ``as_table``, with other helper methods of ``as_p``
    
  948. and ``as_ul`` being available. The rendering of the formset can be customized
    
  949. by specifying the ``template_name`` attribute, or more generally by
    
  950. :ref:`overriding the default template <overriding-built-in-formset-templates>`.
    
  951. 
    
  952. .. versionchanged:: 4.0
    
  953. 
    
  954.     Rendering of formsets was moved to the template engine.
    
  955. 
    
  956. .. _manually-rendered-can-delete-and-can-order:
    
  957. 
    
  958. Manually rendered ``can_delete`` and ``can_order``
    
  959. --------------------------------------------------
    
  960. 
    
  961. If you manually render fields in the template, you can render
    
  962. ``can_delete`` parameter with ``{{ form.DELETE }}``:
    
  963. 
    
  964. .. code-block:: html+django
    
  965. 
    
  966.     <form method="post">
    
  967.         {{ formset.management_form }}
    
  968.         {% for form in formset %}
    
  969.             <ul>
    
  970.                 <li>{{ form.title }}</li>
    
  971.                 <li>{{ form.pub_date }}</li>
    
  972.                 {% if formset.can_delete %}
    
  973.                     <li>{{ form.DELETE }}</li>
    
  974.                 {% endif %}
    
  975.             </ul>
    
  976.         {% endfor %}
    
  977.     </form>
    
  978. 
    
  979. 
    
  980. Similarly, if the formset has the ability to order (``can_order=True``), it is
    
  981. possible to render it with ``{{ form.ORDER }}``.
    
  982. 
    
  983. .. _multiple-formsets-in-view:
    
  984. 
    
  985. Using more than one formset in a view
    
  986. -------------------------------------
    
  987. 
    
  988. You are able to use more than one formset in a view if you like. Formsets
    
  989. borrow much of its behavior from forms. With that said you are able to use
    
  990. ``prefix`` to prefix formset form field names with a given value to allow
    
  991. more than one formset to be sent to a view without name clashing. Let's take
    
  992. a look at how this might be accomplished::
    
  993. 
    
  994.     from django.forms import formset_factory
    
  995.     from django.shortcuts import render
    
  996.     from myapp.forms import ArticleForm, BookForm
    
  997. 
    
  998.     def manage_articles(request):
    
  999.         ArticleFormSet = formset_factory(ArticleForm)
    
  1000.         BookFormSet = formset_factory(BookForm)
    
  1001.         if request.method == 'POST':
    
  1002.             article_formset = ArticleFormSet(request.POST, request.FILES, prefix='articles')
    
  1003.             book_formset = BookFormSet(request.POST, request.FILES, prefix='books')
    
  1004.             if article_formset.is_valid() and book_formset.is_valid():
    
  1005.                 # do something with the cleaned_data on the formsets.
    
  1006.                 pass
    
  1007.         else:
    
  1008.             article_formset = ArticleFormSet(prefix='articles')
    
  1009.             book_formset = BookFormSet(prefix='books')
    
  1010.         return render(request, 'manage_articles.html', {
    
  1011.             'article_formset': article_formset,
    
  1012.             'book_formset': book_formset,
    
  1013.         })
    
  1014. 
    
  1015. You would then render the formsets as normal. It is important to point out
    
  1016. that you need to pass ``prefix`` on both the POST and non-POST cases so that
    
  1017. it is rendered and processed correctly.
    
  1018. 
    
  1019. Each formset's :ref:`prefix <formset-prefix>` replaces the default ``form``
    
  1020. prefix that's added to each field's ``name`` and ``id`` HTML attributes.