formsets.txt 40 KB

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