formsets.txt 28 KB

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