formsets.txt 27 KB

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