formsets.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. .. _topics-forms-formsets:
  2. .. _formsets:
  3. Formsets
  4. ========
  5. A formset is a layer of abstraction to working 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.forms:
  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 form. This is because by default the
  25. ``formset_factory`` defines one extra form. This can be controlled with the
  26. ``extra`` parameter::
  27. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
  28. Using initial data with a formset
  29. ---------------------------------
  30. Initial data is what drives the main usability of a formset. As shown above
  31. you can define the number of extra forms. What this means is that you are
  32. telling the formset how many additional forms to show in addition to the
  33. number of forms it generates from the initial data. Lets take a look at an
  34. example::
  35. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
  36. >>> formset = ArticleFormSet(initial=[
  37. ... {'title': u'Django is now open source',
  38. ... 'pub_date': datetime.date.today()},
  39. ... ])
  40. >>> for form in formset.forms:
  41. ... print form.as_table()
  42. <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>
  43. <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>
  44. <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>
  45. <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>
  46. <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>
  47. <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>
  48. There are now a total of three forms showing above. One for the initial data
  49. that was passed in and two extra forms. Also note that we are passing in a
  50. list of dictionaries as the initial data.
  51. Limiting the maximum number of forms
  52. ------------------------------------
  53. The ``max_num`` parameter to ``formset_factory`` gives you the ability to
  54. force the maximum number of forms the formset will display::
  55. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
  56. >>> formset = ArticleFormset()
  57. >>> for form in formset.forms:
  58. ... print form.as_table()
  59. <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>
  60. <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>
  61. A ``max_num`` value of ``0`` (the default) puts no limit on the number forms
  62. displayed.
  63. Formset validation
  64. ------------------
  65. Validation with a formset is about identical to a regular ``Form``. There is
  66. an ``is_valid`` method on the formset to provide a convenient way to validate
  67. each form in the formset::
  68. >>> ArticleFormSet = formset_factory(ArticleForm)
  69. >>> formset = ArticleFormSet({})
  70. >>> formset.is_valid()
  71. True
  72. We passed in no data to the formset which is resulting in a valid form. The
  73. formset is smart enough to ignore extra forms that were not changed. If we
  74. attempt to provide an article, but fail to do so::
  75. >>> data = {
  76. ... 'form-TOTAL_FORMS': u'1',
  77. ... 'form-INITIAL_FORMS': u'1',
  78. ... 'form-0-title': u'Test',
  79. ... 'form-0-pub_date': u'',
  80. ... }
  81. >>> formset = ArticleFormSet(data)
  82. >>> formset.is_valid()
  83. False
  84. >>> formset.errors
  85. [{'pub_date': [u'This field is required.']}]
  86. As we can see the formset properly performed validation and gave us the
  87. expected errors.
  88. .. _understanding-the-managementform:
  89. Understanding the ManagementForm
  90. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  91. You may have noticed the additional data that was required in the formset's
  92. data above. This data is coming from the ``ManagementForm``. This form is
  93. dealt with internally to the formset. If you don't use it, it will result in
  94. an exception::
  95. >>> data = {
  96. ... 'form-0-title': u'Test',
  97. ... 'form-0-pub_date': u'',
  98. ... }
  99. >>> formset = ArticleFormSet(data)
  100. Traceback (most recent call last):
  101. ...
  102. django.forms.util.ValidationError: [u'ManagementForm data is missing or has been tampered with']
  103. It is used to keep track of how many form instances are being displayed. If
  104. you are adding new forms via JavaScript, you should increment the count fields
  105. in this form as well.
  106. .. versionadded:: 1.1
  107. ``total_form_count`` and ``initial_form_count``
  108. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  109. ``BaseModelFormSet`` has a couple of methods that are closely related to the
  110. ``ManagementForm``, ``total_form_count`` and ``initial_form_count``.
  111. ``total_form_count`` returns the total number of forms in this formset.
  112. ``initial_form_count`` returns the number of forms in the formset that were
  113. pre-filled, and is also used to determine how many forms are required. You
  114. will probably never need to override either of these methods, so please be
  115. sure you understand what they do before doing so.
  116. Custom formset validation
  117. ~~~~~~~~~~~~~~~~~~~~~~~~~
  118. A formset has a ``clean`` method similar to the one on a ``Form`` class. This
  119. is where you define your own validation that deals at the formset level::
  120. >>> from django.forms.formsets import BaseFormSet
  121. >>> class BaseArticleFormSet(BaseFormSet):
  122. ... def clean(self):
  123. ... raise forms.ValidationError, u'An error occured.'
  124. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
  125. >>> formset = ArticleFormSet({})
  126. >>> formset.is_valid()
  127. False
  128. >>> formset.non_form_errors()
  129. [u'An error occured.']
  130. The formset ``clean`` method is called after all the ``Form.clean`` methods
  131. have been called. The errors will be found using the ``non_form_errors()``
  132. method on the formset.
  133. Dealing with ordering and deletion of forms
  134. -------------------------------------------
  135. Common use cases with a formset is dealing with ordering and deletion of the
  136. form instances. This has been dealt with for you. The ``formset_factory``
  137. provides two optional parameters ``can_order`` and ``can_delete`` that will do
  138. the extra work of adding the extra fields and providing simpler ways of
  139. getting to that data.
  140. ``can_order``
  141. ~~~~~~~~~~~~~
  142. Default: ``False``
  143. Lets create a formset with the ability to order::
  144. >>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)
  145. >>> formset = ArticleFormSet(initial=[
  146. ... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  147. ... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  148. ... ])
  149. >>> for form in formset.forms:
  150. ... print form.as_table()
  151. <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>
  152. <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>
  153. <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>
  154. <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>
  155. <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>
  156. <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>
  157. <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>
  158. <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>
  159. <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>
  160. This adds an additional field to each form. This new field is named ``ORDER``
  161. and is an ``forms.IntegerField``. For the forms that came from the initial
  162. data it automatically assigned them a numeric value. Lets look at what will
  163. happen when the user changes these values::
  164. >>> data = {
  165. ... 'form-TOTAL_FORMS': u'3',
  166. ... 'form-INITIAL_FORMS': u'2',
  167. ... 'form-0-title': u'Article #1',
  168. ... 'form-0-pub_date': u'2008-05-10',
  169. ... 'form-0-ORDER': u'2',
  170. ... 'form-1-title': u'Article #2',
  171. ... 'form-1-pub_date': u'2008-05-11',
  172. ... 'form-1-ORDER': u'1',
  173. ... 'form-2-title': u'Article #3',
  174. ... 'form-2-pub_date': u'2008-05-01',
  175. ... 'form-2-ORDER': u'0',
  176. ... }
  177. >>> formset = ArticleFormSet(data, initial=[
  178. ... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  179. ... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  180. ... ])
  181. >>> formset.is_valid()
  182. True
  183. >>> for form in formset.ordered_forms:
  184. ... print form.cleaned_data
  185. {'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': u'Article #3'}
  186. {'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': u'Article #2'}
  187. {'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': u'Article #1'}
  188. ``can_delete``
  189. ~~~~~~~~~~~~~~
  190. Default: ``False``
  191. Lets create a formset with the ability to delete::
  192. >>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True)
  193. >>> formset = ArticleFormSet(initial=[
  194. ... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  195. ... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  196. ... ])
  197. >>> for form in formset.forms:
  198. .... print form.as_table()
  199. <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" />
  200. <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>
  201. <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>
  202. <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>
  203. <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>
  204. <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>
  205. <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>
  206. <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>
  207. <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>
  208. <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>
  209. Similar to ``can_order`` this adds a new field to each form named ``DELETE``
  210. and is a ``forms.BooleanField``. When data comes through marking any of the
  211. delete fields you can access them with ``deleted_forms``::
  212. >>> data = {
  213. ... 'form-TOTAL_FORMS': u'3',
  214. ... 'form-INITIAL_FORMS': u'2',
  215. ... 'form-0-title': u'Article #1',
  216. ... 'form-0-pub_date': u'2008-05-10',
  217. ... 'form-0-DELETE': u'on',
  218. ... 'form-1-title': u'Article #2',
  219. ... 'form-1-pub_date': u'2008-05-11',
  220. ... 'form-1-DELETE': u'',
  221. ... 'form-2-title': u'',
  222. ... 'form-2-pub_date': u'',
  223. ... 'form-2-DELETE': u'',
  224. ... }
  225. >>> formset = ArticleFormSet(data, initial=[
  226. ... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  227. ... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  228. ... ])
  229. >>> [form.cleaned_data for form in formset.deleted_forms]
  230. [{'DELETE': True, 'pub_date': datetime.date(2008, 5, 10), 'title': u'Article #1'}]
  231. Adding additional fields to a formset
  232. -------------------------------------
  233. If you need to add additional fields to the formset this can be easily
  234. accomplished. The formset base class provides an ``add_fields`` method. You
  235. can simply override this method to add your own fields or even redefine the
  236. default fields/attributes of the order and deletion fields::
  237. >>> class BaseArticleFormSet(BaseFormSet):
  238. ... def add_fields(self, form, index):
  239. ... super(BaseArticleFormSet, self).add_fields(form, index)
  240. ... form.fields["my_field"] = forms.CharField()
  241. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
  242. >>> formset = ArticleFormSet()
  243. >>> for form in formset.forms:
  244. ... print form.as_table()
  245. <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>
  246. <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>
  247. <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>
  248. Using a formset in views and templates
  249. --------------------------------------
  250. Using a formset inside a view is as easy as using a regular ``Form`` class.
  251. The only thing you will want to be aware of is making sure to use the
  252. management form inside the template. Let's look at a sample view:
  253. .. code-block:: python
  254. def manage_articles(request):
  255. ArticleFormSet = formset_factory(ArticleForm)
  256. if request.method == 'POST':
  257. formset = ArticleFormSet(request.POST, request.FILES)
  258. if formset.is_valid():
  259. # do something with the formset.cleaned_data
  260. else:
  261. formset = ArticleFormSet()
  262. return render_to_response('manage_articles.html', {'formset': formset})
  263. The ``manage_articles.html`` template might look like this:
  264. .. code-block:: html+django
  265. <form method="POST" action="">
  266. {{ formset.management_form }}
  267. <table>
  268. {% for form in formset.forms %}
  269. {{ form }}
  270. {% endfor %}
  271. </table>
  272. </form>
  273. However the above can be slightly shortcutted and let the formset itself deal
  274. with the management form:
  275. .. code-block:: html+django
  276. <form method="POST" action="">
  277. <table>
  278. {{ formset }}
  279. </table>
  280. </form>
  281. The above ends up calling the ``as_table`` method on the formset class.
  282. Using more than one formset in a view
  283. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  284. You are able to use more than one formset in a view if you like. Formsets
  285. borrow much of its behavior from forms. With that said you are able to use
  286. ``prefix`` to prefix formset form field names with a given value to allow
  287. more than one formset to be sent to a view without name clashing. Lets take
  288. a look at how this might be accomplished:
  289. .. code-block:: python
  290. def manage_articles(request):
  291. ArticleFormSet = formset_factory(ArticleForm)
  292. BookFormSet = formset_factory(BookForm)
  293. if request.method == 'POST':
  294. article_formset = ArticleFormSet(request.POST, request.FILES, prefix='articles')
  295. book_formset = BookFormSet(request.POST, request.FILES, prefix='books')
  296. if article_formset.is_valid() and book_formset.is_valid():
  297. # do something with the cleaned_data on the formsets.
  298. else:
  299. article_formset = ArticleFormSet(prefix='articles')
  300. book_formset = BookFormSet(prefix='books')
  301. return render_to_response('manage_articles.html', {
  302. 'article_formset': article_formset,
  303. 'book_formset': book_formset,
  304. })
  305. You would then render the formsets as normal. It is important to point out
  306. that you need to pass ``prefix`` on both the POST and non-POST cases so that
  307. it is rendered and processed correctly.