formsets.txt 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. ========
  2. Formsets
  3. ========
  4. .. module:: django.forms.formsets
  5. :synopsis: An abstraction for working with multiple forms on the same page.
  6. .. class:: BaseFormSet
  7. A formset is a layer of abstraction to work with multiple forms on the same
  8. page. It can be best compared to a data grid. Let's say you have the following
  9. form::
  10. >>> from django import forms
  11. >>> class ArticleForm(forms.Form):
  12. ... title = forms.CharField()
  13. ... pub_date = forms.DateField()
  14. You might want to allow the user to create several articles at once. To create
  15. a formset out of an ``ArticleForm`` you would do::
  16. >>> from django.forms import formset_factory
  17. >>> ArticleFormSet = formset_factory(ArticleForm)
  18. You now have created a formset named ``ArticleFormSet``. The formset gives you
  19. the ability to iterate over the forms in the formset and display them as you
  20. would with a regular form::
  21. >>> formset = ArticleFormSet()
  22. >>> for form in formset:
  23. ... print(form.as_table())
  24. <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>
  25. <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>
  26. As you can see it only displayed one empty form. The number of empty forms
  27. that is displayed is controlled by the ``extra`` parameter. By default,
  28. :func:`~django.forms.formsets.formset_factory` defines one extra form; the
  29. following example will display two blank forms::
  30. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
  31. Iterating over the ``formset`` will render the forms in the order they were
  32. created. You can change this order by providing an alternate implementation for
  33. the ``__iter__()`` method.
  34. Formsets can also be indexed into, which returns the corresponding form. If you
  35. override ``__iter__``, you will need to also override ``__getitem__`` to have
  36. matching behavior.
  37. .. _formsets-initial-data:
  38. Using initial data with a formset
  39. =================================
  40. Initial data is what drives the main usability of a formset. As shown above
  41. you can define the number of extra forms. What this means is that you are
  42. telling the formset how many additional forms to show in addition to the
  43. number of forms it generates from the initial data. Let's take a look at an
  44. example::
  45. >>> import datetime
  46. >>> from django.forms import formset_factory
  47. >>> from myapp.forms import ArticleForm
  48. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
  49. >>> formset = ArticleFormSet(initial=[
  50. ... {'title': 'Django is now open source',
  51. ... 'pub_date': datetime.date.today(),}
  52. ... ])
  53. >>> for form in formset:
  54. ... print(form.as_table())
  55. <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>
  56. <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>
  57. <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>
  58. <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>
  59. <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>
  60. <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>
  61. There are now a total of three forms showing above. One for the initial data
  62. that was passed in and two extra forms. Also note that we are passing in a
  63. list of dictionaries as the initial data.
  64. If you use an ``initial`` for displaying a formset, you should pass the same
  65. ``initial`` when processing that formset's submission so that the formset can
  66. detect which forms were changed by the user. For example, you might have
  67. something like: ``ArticleFormSet(request.POST, initial=[...])``.
  68. .. seealso::
  69. :ref:`Creating formsets from models with model formsets <model-formsets>`.
  70. .. _formsets-max-num:
  71. Limiting the maximum number of forms
  72. ====================================
  73. The ``max_num`` parameter to :func:`~django.forms.formsets.formset_factory`
  74. gives you the ability to limit the number of forms the formset will display::
  75. >>> from django.forms import formset_factory
  76. >>> from myapp.forms import ArticleForm
  77. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
  78. >>> formset = ArticleFormSet()
  79. >>> for form in formset:
  80. ... print(form.as_table())
  81. <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>
  82. <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>
  83. If the value of ``max_num`` is greater than the number of existing items in the
  84. initial data, up to ``extra`` additional blank forms will be added to the
  85. formset, so long as the total number of forms does not exceed ``max_num``. For
  86. example, if ``extra=2`` and ``max_num=2`` and the formset is initialized with
  87. one ``initial`` item, a form for the initial item and one blank form will be
  88. displayed.
  89. If the number of items in the initial data exceeds ``max_num``, all initial
  90. data forms will be displayed regardless of the value of ``max_num`` and no
  91. extra forms will be displayed. For example, if ``extra=3`` and ``max_num=1``
  92. and the formset is initialized with two initial items, two forms with the
  93. initial data will be displayed.
  94. A ``max_num`` value of ``None`` (the default) puts a high limit on the number
  95. of forms displayed (1000). In practice this is equivalent to no limit.
  96. By default, ``max_num`` only affects how many forms are displayed and does not
  97. affect validation. If ``validate_max=True`` is passed to the
  98. :func:`~django.forms.formsets.formset_factory`, then ``max_num`` will affect
  99. validation. See :ref:`validate_max`.
  100. Formset validation
  101. ==================
  102. Validation with a formset is almost identical to a regular ``Form``. There is
  103. an ``is_valid`` method on the formset to provide a convenient way to validate
  104. all forms in the formset::
  105. >>> from django.forms import formset_factory
  106. >>> from myapp.forms import ArticleForm
  107. >>> ArticleFormSet = formset_factory(ArticleForm)
  108. >>> data = {
  109. ... 'form-TOTAL_FORMS': '1',
  110. ... 'form-INITIAL_FORMS': '0',
  111. ... 'form-MAX_NUM_FORMS': '',
  112. ... }
  113. >>> formset = ArticleFormSet(data)
  114. >>> formset.is_valid()
  115. True
  116. We passed in no data to the formset which is resulting in a valid form. The
  117. formset is smart enough to ignore extra forms that were not changed. If we
  118. provide an invalid article::
  119. >>> data = {
  120. ... 'form-TOTAL_FORMS': '2',
  121. ... 'form-INITIAL_FORMS': '0',
  122. ... 'form-MAX_NUM_FORMS': '',
  123. ... 'form-0-title': 'Test',
  124. ... 'form-0-pub_date': '1904-06-16',
  125. ... 'form-1-title': 'Test',
  126. ... 'form-1-pub_date': '', # <-- this date is missing but required
  127. ... }
  128. >>> formset = ArticleFormSet(data)
  129. >>> formset.is_valid()
  130. False
  131. >>> formset.errors
  132. [{}, {'pub_date': ['This field is required.']}]
  133. As we can see, ``formset.errors`` is a list whose entries correspond to the
  134. forms in the formset. Validation was performed for each of the two forms, and
  135. the expected error message appears for the second item.
  136. Just like when using a normal ``Form``, each field in a formset's forms may
  137. include HTML attributes such as ``maxlength`` for browser validation. However,
  138. form fields of formsets won't include the ``required`` attribute as that
  139. validation may be incorrect when adding and deleting forms.
  140. .. method:: BaseFormSet.total_error_count()
  141. To check how many errors there are in the formset, we can use the
  142. ``total_error_count`` method::
  143. >>> # Using the previous example
  144. >>> formset.errors
  145. [{}, {'pub_date': ['This field is required.']}]
  146. >>> len(formset.errors)
  147. 2
  148. >>> formset.total_error_count()
  149. 1
  150. We can also check if form data differs from the initial data (i.e. the form was
  151. sent without any data)::
  152. >>> data = {
  153. ... 'form-TOTAL_FORMS': '1',
  154. ... 'form-INITIAL_FORMS': '0',
  155. ... 'form-MAX_NUM_FORMS': '',
  156. ... 'form-0-title': '',
  157. ... 'form-0-pub_date': '',
  158. ... }
  159. >>> formset = ArticleFormSet(data)
  160. >>> formset.has_changed()
  161. False
  162. .. _understanding-the-managementform:
  163. Understanding the ``ManagementForm``
  164. ------------------------------------
  165. You may have noticed the additional data (``form-TOTAL_FORMS``,
  166. ``form-INITIAL_FORMS`` and ``form-MAX_NUM_FORMS``) that was required
  167. in the formset's data above. This data is required for the
  168. ``ManagementForm``. This form is used by the formset to manage the
  169. collection of forms contained in the formset. If you don't provide
  170. this management data, an exception will be raised::
  171. >>> data = {
  172. ... 'form-0-title': 'Test',
  173. ... 'form-0-pub_date': '',
  174. ... }
  175. >>> formset = ArticleFormSet(data)
  176. >>> formset.is_valid()
  177. Traceback (most recent call last):
  178. ...
  179. django.forms.utils.ValidationError: ['ManagementForm data is missing or has been tampered with']
  180. It is used to keep track of how many form instances are being displayed. If
  181. you are adding new forms via JavaScript, you should increment the count fields
  182. in this form as well. On the other hand, if you are using JavaScript to allow
  183. deletion of existing objects, then you need to ensure the ones being removed
  184. are properly marked for deletion by including ``form-#-DELETE`` in the ``POST``
  185. data. It is expected that all forms are present in the ``POST`` data regardless.
  186. The management form is available as an attribute of the formset
  187. itself. When rendering a formset in a template, you can include all
  188. the management data by rendering ``{{ my_formset.management_form }}``
  189. (substituting the name of your formset as appropriate).
  190. ``total_form_count`` and ``initial_form_count``
  191. -----------------------------------------------
  192. ``BaseFormSet`` has a couple of methods that are closely related to the
  193. ``ManagementForm``, ``total_form_count`` and ``initial_form_count``.
  194. ``total_form_count`` returns the total number of forms in this formset.
  195. ``initial_form_count`` returns the number of forms in the formset that were
  196. pre-filled, and is also used to determine how many forms are required. You
  197. will probably never need to override either of these methods, so please be
  198. sure you understand what they do before doing so.
  199. .. _empty_form:
  200. ``empty_form``
  201. --------------
  202. ``BaseFormSet`` provides an additional attribute ``empty_form`` which returns
  203. a form instance with a prefix of ``__prefix__`` for easier use in dynamic
  204. forms with JavaScript.
  205. Custom formset validation
  206. -------------------------
  207. A formset has a ``clean`` method similar to the one on a ``Form`` class. This
  208. is where you define your own validation that works at the formset level::
  209. >>> from django.forms import BaseFormSet
  210. >>> from django.forms import formset_factory
  211. >>> from myapp.forms import ArticleForm
  212. >>> class BaseArticleFormSet(BaseFormSet):
  213. ... def clean(self):
  214. ... """Checks that no two articles have the same title."""
  215. ... if any(self.errors):
  216. ... # Don't bother validating the formset unless each form is valid on its own
  217. ... return
  218. ... titles = []
  219. ... for form in self.forms:
  220. ... title = form.cleaned_data['title']
  221. ... if title in titles:
  222. ... raise forms.ValidationError("Articles in a set must have distinct titles.")
  223. ... titles.append(title)
  224. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
  225. >>> data = {
  226. ... 'form-TOTAL_FORMS': '2',
  227. ... 'form-INITIAL_FORMS': '0',
  228. ... 'form-MAX_NUM_FORMS': '',
  229. ... 'form-0-title': 'Test',
  230. ... 'form-0-pub_date': '1904-06-16',
  231. ... 'form-1-title': 'Test',
  232. ... 'form-1-pub_date': '1912-06-23',
  233. ... }
  234. >>> formset = ArticleFormSet(data)
  235. >>> formset.is_valid()
  236. False
  237. >>> formset.errors
  238. [{}, {}]
  239. >>> formset.non_form_errors()
  240. ['Articles in a set must have distinct titles.']
  241. The formset ``clean`` method is called after all the ``Form.clean`` methods
  242. have been called. The errors will be found using the ``non_form_errors()``
  243. method on the formset.
  244. Validating the number of forms in a formset
  245. ===========================================
  246. Django provides a couple ways to validate the minimum or maximum number of
  247. submitted forms. Applications which need more customizable validation of the
  248. number of forms should use custom formset validation.
  249. .. _validate_max:
  250. ``validate_max``
  251. ----------------
  252. If ``validate_max=True`` is passed to
  253. :func:`~django.forms.formsets.formset_factory`, validation will also check
  254. that the number of forms in the data set, minus those marked for
  255. deletion, is less than or equal to ``max_num``.
  256. >>> from django.forms import formset_factory
  257. >>> from myapp.forms import ArticleForm
  258. >>> ArticleFormSet = formset_factory(ArticleForm, max_num=1, validate_max=True)
  259. >>> data = {
  260. ... 'form-TOTAL_FORMS': '2',
  261. ... 'form-INITIAL_FORMS': '0',
  262. ... 'form-MIN_NUM_FORMS': '',
  263. ... 'form-MAX_NUM_FORMS': '',
  264. ... 'form-0-title': 'Test',
  265. ... 'form-0-pub_date': '1904-06-16',
  266. ... 'form-1-title': 'Test 2',
  267. ... 'form-1-pub_date': '1912-06-23',
  268. ... }
  269. >>> formset = ArticleFormSet(data)
  270. >>> formset.is_valid()
  271. False
  272. >>> formset.errors
  273. [{}, {}]
  274. >>> formset.non_form_errors()
  275. ['Please submit 1 or fewer forms.']
  276. ``validate_max=True`` validates against ``max_num`` strictly even if
  277. ``max_num`` was exceeded because the amount of initial data supplied was
  278. excessive.
  279. .. note::
  280. Regardless of ``validate_max``, if the number of forms in a data set
  281. exceeds ``max_num`` by more than 1000, then the form will fail to validate
  282. as if ``validate_max`` were set, and additionally only the first 1000
  283. forms above ``max_num`` will be validated. The remainder will be
  284. truncated entirely. This is to protect against memory exhaustion attacks
  285. using forged POST requests.
  286. ``validate_min``
  287. ----------------
  288. If ``validate_min=True`` is passed to
  289. :func:`~django.forms.formsets.formset_factory`, validation will also check
  290. that the number of forms in the data set, minus those marked for
  291. deletion, is greater than or equal to ``min_num``.
  292. >>> from django.forms import formset_factory
  293. >>> from myapp.forms import ArticleForm
  294. >>> ArticleFormSet = formset_factory(ArticleForm, min_num=3, validate_min=True)
  295. >>> data = {
  296. ... 'form-TOTAL_FORMS': '2',
  297. ... 'form-INITIAL_FORMS': '0',
  298. ... 'form-MIN_NUM_FORMS': '',
  299. ... 'form-MAX_NUM_FORMS': '',
  300. ... 'form-0-title': 'Test',
  301. ... 'form-0-pub_date': '1904-06-16',
  302. ... 'form-1-title': 'Test 2',
  303. ... 'form-1-pub_date': '1912-06-23',
  304. ... }
  305. >>> formset = ArticleFormSet(data)
  306. >>> formset.is_valid()
  307. False
  308. >>> formset.errors
  309. [{}, {}]
  310. >>> formset.non_form_errors()
  311. ['Please submit 3 or more forms.']
  312. Dealing with ordering and deletion of forms
  313. ===========================================
  314. The :func:`~django.forms.formsets.formset_factory` provides two optional
  315. parameters ``can_order`` and ``can_delete`` to help with ordering of forms in
  316. formsets and deletion of forms from a formset.
  317. ``can_order``
  318. -------------
  319. .. attribute:: BaseFormSet.can_order
  320. Default: ``False``
  321. Lets you create a formset with the ability to order::
  322. >>> from django.forms import formset_factory
  323. >>> from myapp.forms import ArticleForm
  324. >>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)
  325. >>> formset = ArticleFormSet(initial=[
  326. ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  327. ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  328. ... ])
  329. >>> for form in formset:
  330. ... print(form.as_table())
  331. <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>
  332. <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>
  333. <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>
  334. <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>
  335. <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>
  336. <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>
  337. <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>
  338. <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>
  339. <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>
  340. This adds an additional field to each form. This new field is named ``ORDER``
  341. and is an ``forms.IntegerField``. For the forms that came from the initial
  342. data it automatically assigned them a numeric value. Let's look at what will
  343. happen when the user changes these values::
  344. >>> data = {
  345. ... 'form-TOTAL_FORMS': '3',
  346. ... 'form-INITIAL_FORMS': '2',
  347. ... 'form-MAX_NUM_FORMS': '',
  348. ... 'form-0-title': 'Article #1',
  349. ... 'form-0-pub_date': '2008-05-10',
  350. ... 'form-0-ORDER': '2',
  351. ... 'form-1-title': 'Article #2',
  352. ... 'form-1-pub_date': '2008-05-11',
  353. ... 'form-1-ORDER': '1',
  354. ... 'form-2-title': 'Article #3',
  355. ... 'form-2-pub_date': '2008-05-01',
  356. ... 'form-2-ORDER': '0',
  357. ... }
  358. >>> formset = ArticleFormSet(data, initial=[
  359. ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  360. ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  361. ... ])
  362. >>> formset.is_valid()
  363. True
  364. >>> for form in formset.ordered_forms:
  365. ... print(form.cleaned_data)
  366. {'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': 'Article #3'}
  367. {'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': 'Article #2'}
  368. {'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': 'Article #1'}
  369. :class:`~django.forms.formsets.BaseFormSet` also provides an
  370. :attr:`~django.forms.formsets.BaseFormSet.ordering_widget` attribute and
  371. :meth:`~django.forms.formsets.BaseFormSet.get_ordering_widget` method that
  372. control the widget used with
  373. :attr:`~django.forms.formsets.BaseFormSet.can_order`.
  374. ``ordering_widget``
  375. ^^^^^^^^^^^^^^^^^^^
  376. .. versionadded:: 3.0
  377. .. attribute:: BaseFormSet.ordering_widget
  378. Default: :class:`~django.forms.NumberInput`
  379. Set ``ordering_widget`` to specify the widget class to be used with
  380. ``can_order``::
  381. >>> from django.forms import BaseFormSet, formset_factory
  382. >>> from myapp.forms import ArticleForm
  383. >>> class BaseArticleFormSet(BaseFormSet):
  384. ... ordering_widget = HiddenInput
  385. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)
  386. ``get_ordering_widget``
  387. ^^^^^^^^^^^^^^^^^^^^^^^
  388. .. versionadded:: 3.0
  389. .. method:: BaseFormSet.get_ordering_widget()
  390. Override ``get_ordering_widget()`` if you need to provide a widget instance for
  391. use with ``can_order``::
  392. >>> from django.forms import BaseFormSet, formset_factory
  393. >>> from myapp.forms import ArticleForm
  394. >>> class BaseArticleFormSet(BaseFormSet):
  395. ... def get_ordering_widget(self):
  396. ... return HiddenInput(attrs={'class': 'ordering'})
  397. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)
  398. ``can_delete``
  399. --------------
  400. .. attribute:: BaseFormSet.can_delete
  401. Default: ``False``
  402. Lets you create a formset with the ability to select forms for deletion::
  403. >>> from django.forms import formset_factory
  404. >>> from myapp.forms import ArticleForm
  405. >>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True)
  406. >>> formset = ArticleFormSet(initial=[
  407. ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  408. ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  409. ... ])
  410. >>> for form in formset:
  411. ... print(form.as_table())
  412. <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>
  413. <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>
  414. <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>
  415. <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>
  416. <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>
  417. <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>
  418. <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>
  419. <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>
  420. <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>
  421. Similar to ``can_order`` this adds a new field to each form named ``DELETE``
  422. and is a ``forms.BooleanField``. When data comes through marking any of the
  423. delete fields you can access them with ``deleted_forms``::
  424. >>> data = {
  425. ... 'form-TOTAL_FORMS': '3',
  426. ... 'form-INITIAL_FORMS': '2',
  427. ... 'form-MAX_NUM_FORMS': '',
  428. ... 'form-0-title': 'Article #1',
  429. ... 'form-0-pub_date': '2008-05-10',
  430. ... 'form-0-DELETE': 'on',
  431. ... 'form-1-title': 'Article #2',
  432. ... 'form-1-pub_date': '2008-05-11',
  433. ... 'form-1-DELETE': '',
  434. ... 'form-2-title': '',
  435. ... 'form-2-pub_date': '',
  436. ... 'form-2-DELETE': '',
  437. ... }
  438. >>> formset = ArticleFormSet(data, initial=[
  439. ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  440. ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  441. ... ])
  442. >>> [form.cleaned_data for form in formset.deleted_forms]
  443. [{'DELETE': True, 'pub_date': datetime.date(2008, 5, 10), 'title': 'Article #1'}]
  444. If you are using a :class:`ModelFormSet<django.forms.models.BaseModelFormSet>`,
  445. model instances for deleted forms will be deleted when you call
  446. ``formset.save()``.
  447. If you call ``formset.save(commit=False)``, objects will not be deleted
  448. automatically. You'll need to call ``delete()`` on each of the
  449. :attr:`formset.deleted_objects
  450. <django.forms.models.BaseModelFormSet.deleted_objects>` to actually delete
  451. them::
  452. >>> instances = formset.save(commit=False)
  453. >>> for obj in formset.deleted_objects:
  454. ... obj.delete()
  455. On the other hand, if you are using a plain ``FormSet``, it's up to you to
  456. handle ``formset.deleted_forms``, perhaps in your formset's ``save()`` method,
  457. as there's no general notion of what it means to delete a form.
  458. Adding additional fields to a formset
  459. =====================================
  460. If you need to add additional fields to the formset this can be easily
  461. accomplished. The formset base class provides an ``add_fields`` method. You
  462. can simply override this method to add your own fields or even redefine the
  463. default fields/attributes of the order and deletion fields::
  464. >>> from django.forms import BaseFormSet
  465. >>> from django.forms import formset_factory
  466. >>> from myapp.forms import ArticleForm
  467. >>> class BaseArticleFormSet(BaseFormSet):
  468. ... def add_fields(self, form, index):
  469. ... super().add_fields(form, index)
  470. ... form.fields["my_field"] = forms.CharField()
  471. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
  472. >>> formset = ArticleFormSet()
  473. >>> for form in formset:
  474. ... print(form.as_table())
  475. <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>
  476. <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>
  477. <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>
  478. .. _custom-formset-form-kwargs:
  479. Passing custom parameters to formset forms
  480. ==========================================
  481. Sometimes your form class takes custom parameters, like ``MyArticleForm``.
  482. You can pass this parameter when instantiating the formset::
  483. >>> from django.forms import BaseFormSet
  484. >>> from django.forms import formset_factory
  485. >>> from myapp.forms import ArticleForm
  486. >>> class MyArticleForm(ArticleForm):
  487. ... def __init__(self, *args, user, **kwargs):
  488. ... self.user = user
  489. ... super().__init__(*args, **kwargs)
  490. >>> ArticleFormSet = formset_factory(MyArticleForm)
  491. >>> formset = ArticleFormSet(form_kwargs={'user': request.user})
  492. The ``form_kwargs`` may also depend on the specific form instance. The formset
  493. base class provides a ``get_form_kwargs`` method. The method takes a single
  494. argument - the index of the form in the formset. The index is ``None`` for the
  495. :ref:`empty_form`::
  496. >>> from django.forms import BaseFormSet
  497. >>> from django.forms import formset_factory
  498. >>> class BaseArticleFormSet(BaseFormSet):
  499. ... def get_form_kwargs(self, index):
  500. ... kwargs = super().get_form_kwargs(index)
  501. ... kwargs['custom_kwarg'] = index
  502. ... return kwargs
  503. .. _formset-prefix:
  504. Customizing a formset's prefix
  505. ==============================
  506. In the rendered HTML, formsets include a prefix on each field's name. By
  507. default, the prefix is ``'form'``, but it can be customized using the formset's
  508. ``prefix`` argument.
  509. For example, in the default case, you might see:
  510. .. code-block:: html
  511. <label for="id_form-0-title">Title:</label>
  512. <input type="text" name="form-0-title" id="id_form-0-title">
  513. But with ``ArticleFormset(prefix='article')`` that becomes:
  514. .. code-block:: html
  515. <label for="id_article-0-title">Title:</label>
  516. <input type="text" name="article-0-title" id="id_article-0-title">
  517. This is useful if you want to :ref:`use more than one formset in a view
  518. <multiple-formsets-in-view>`.
  519. Using a formset in views and templates
  520. ======================================
  521. Using a formset inside a view is as easy as using a regular ``Form`` class.
  522. The only thing you will want to be aware of is making sure to use the
  523. management form inside the template. Let's look at a sample view::
  524. from django.forms import formset_factory
  525. from django.shortcuts import render
  526. from myapp.forms import ArticleForm
  527. def manage_articles(request):
  528. ArticleFormSet = formset_factory(ArticleForm)
  529. if request.method == 'POST':
  530. formset = ArticleFormSet(request.POST, request.FILES)
  531. if formset.is_valid():
  532. # do something with the formset.cleaned_data
  533. pass
  534. else:
  535. formset = ArticleFormSet()
  536. return render(request, 'manage_articles.html', {'formset': formset})
  537. The ``manage_articles.html`` template might look like this:
  538. .. code-block:: html+django
  539. <form method="post">
  540. {{ formset.management_form }}
  541. <table>
  542. {% for form in formset %}
  543. {{ form }}
  544. {% endfor %}
  545. </table>
  546. </form>
  547. However there's a slight shortcut for the above by letting the formset itself
  548. deal with the management form:
  549. .. code-block:: html+django
  550. <form method="post">
  551. <table>
  552. {{ formset }}
  553. </table>
  554. </form>
  555. The above ends up calling the ``as_table`` method on the formset class.
  556. .. _manually-rendered-can-delete-and-can-order:
  557. Manually rendered ``can_delete`` and ``can_order``
  558. --------------------------------------------------
  559. If you manually render fields in the template, you can render
  560. ``can_delete`` parameter with ``{{ form.DELETE }}``:
  561. .. code-block:: html+django
  562. <form method="post">
  563. {{ formset.management_form }}
  564. {% for form in formset %}
  565. <ul>
  566. <li>{{ form.title }}</li>
  567. <li>{{ form.pub_date }}</li>
  568. {% if formset.can_delete %}
  569. <li>{{ form.DELETE }}</li>
  570. {% endif %}
  571. </ul>
  572. {% endfor %}
  573. </form>
  574. Similarly, if the formset has the ability to order (``can_order=True``), it is
  575. possible to render it with ``{{ form.ORDER }}``.
  576. .. _multiple-formsets-in-view:
  577. Using more than one formset in a view
  578. -------------------------------------
  579. You are able to use more than one formset in a view if you like. Formsets
  580. borrow much of its behavior from forms. With that said you are able to use
  581. ``prefix`` to prefix formset form field names with a given value to allow
  582. more than one formset to be sent to a view without name clashing. Let's take
  583. a look at how this might be accomplished::
  584. from django.forms import formset_factory
  585. from django.shortcuts import render
  586. from myapp.forms import ArticleForm, BookForm
  587. def manage_articles(request):
  588. ArticleFormSet = formset_factory(ArticleForm)
  589. BookFormSet = formset_factory(BookForm)
  590. if request.method == 'POST':
  591. article_formset = ArticleFormSet(request.POST, request.FILES, prefix='articles')
  592. book_formset = BookFormSet(request.POST, request.FILES, prefix='books')
  593. if article_formset.is_valid() and book_formset.is_valid():
  594. # do something with the cleaned_data on the formsets.
  595. pass
  596. else:
  597. article_formset = ArticleFormSet(prefix='articles')
  598. book_formset = BookFormSet(prefix='books')
  599. return render(request, 'manage_articles.html', {
  600. 'article_formset': article_formset,
  601. 'book_formset': book_formset,
  602. })
  603. You would then render the formsets as normal. It is important to point out
  604. that you need to pass ``prefix`` on both the POST and non-POST cases so that
  605. it is rendered and processed correctly.
  606. Each formset's :ref:`prefix <formset-prefix>` replaces the default ``form``
  607. prefix that's added to each field's ``name`` and ``id`` HTML attributes.