PageRenderTime 39ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/topics/forms/formsets.txt

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