formsets.txt 39 KB

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