formsets.txt 27 KB

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