formsets.txt 40 KB

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