formsets.txt 40 KB

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