formsets.txt 29 KB

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