formsets.txt 33 KB

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