formsets.txt 25 KB

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