formsets.txt 21 KB

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