Debian Codegraph @

docs/topics/forms/formsets.txt

raw
1 ========
2 Formsets
3 ========
4
5 .. currentmodule:: django.forms.formsets
6
7 .. class:: BaseFormSet
8
9 A formset is a layer of abstraction to work with multiple forms on the same
10 page. It can be best compared to a data grid. Let's say you have the following
11 form:
12
13 .. code-block:: pycon
14
15 >>> from django import forms
16 >>> class ArticleForm(forms.Form):
17 ... title = forms.CharField()
18 ... pub_date = forms.DateField()
19 ...
20
21 You might want to allow the user to create several articles at once. To create
22 a formset out of an ``ArticleForm`` you would do:
23
24 .. code-block:: pycon
25
26 >>> from django.forms import formset_factory
27 >>> ArticleFormSet = formset_factory(ArticleForm)
28
29 You now have created a formset class named ``ArticleFormSet``.
30 Instantiating the formset gives you the ability to iterate over the forms
31 in the formset and display them as you would with a regular form:
32
33 .. code-block:: pycon
34
35 >>> formset = ArticleFormSet()
36 >>> for form in formset:
37 ... print(form)
38 ...
39 <div><label for="id_form-0-title">Title:</label><input type="text" name="form-0-title" id="id_form-0-title"></div>
40 <div><label for="id_form-0-pub_date">Pub date:</label><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></div>
41
42 As you can see it only displayed one empty form. The number of empty forms
43 that is displayed is controlled by the ``extra`` parameter. By default,
44 :func:`~django.forms.formsets.formset_factory` defines one extra form; the
45 following example will create a formset class to display two blank forms:
46
47 .. code-block:: pycon
48
49 >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
50
51 Formsets can be iterated and indexed, accessing forms in the order they were
52 created. You can reorder the forms by overriding the default
53 :py:meth:`iteration <object.__iter__>` and
54 :py:meth:`indexing <object.__getitem__>` behavior if needed.
55
56 .. _formsets-initial-data:
57
58 Using initial data with a formset
59 =================================
60
61 Initial data is what drives the main usability of a formset. As shown above
62 you can define the number of extra forms. What this means is that you are
63 telling the formset how many additional forms to show in addition to the
64 number of forms it generates from the initial data. Let's take a look at an
65 example:
66
67 .. code-block:: pycon
68
69 >>> import datetime
70 >>> from django.forms import formset_factory
71 >>> from myapp.forms import ArticleForm
72 >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
73 >>> formset = ArticleFormSet(
74 ... initial=[
75 ... {
76 ... "title": "Django is now open source",
77 ... "pub_date": datetime.date.today(),
78 ... }
79 ... ]
80 ... )
81
82 >>> for form in formset:
83 ... print(form)
84 ...
85 <div><label for="id_form-0-title">Title:</label><input type="text" name="form-0-title" value="Django is now open source" id="id_form-0-title"></div>
86 <div><label for="id_form-0-pub_date">Pub date:</label><input type="text" name="form-0-pub_date" value="2023-02-11" id="id_form-0-pub_date"></div>
87 <div><label for="id_form-1-title">Title:</label><input type="text" name="form-1-title" id="id_form-1-title"></div>
88 <div><label for="id_form-1-pub_date">Pub date:</label><input type="text" name="form-1-pub_date" id="id_form-1-pub_date"></div>
89 <div><label for="id_form-2-title">Title:</label><input type="text" name="form-2-title" id="id_form-2-title"></div>
90 <div><label for="id_form-2-pub_date">Pub date:</label><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></div>
91
92 There are now a total of three forms showing above. One for the initial data
93 that was passed in and two extra forms. Also note that we are passing in a
94 list of dictionaries as the initial data.
95
96 If you use an ``initial`` for displaying a formset, you should pass the same
97 ``initial`` when processing that formset's submission so that the formset can
98 detect which forms were changed by the user. For example, you might have
99 something like: ``ArticleFormSet(request.POST, initial=[...])``.
100
101 .. seealso::
102
103 :ref:`Creating formsets from models with model formsets <model-formsets>`.
104
105 .. _formsets-max-num:
106
107 Limiting the maximum number of forms
108 ====================================
109
110 The ``max_num`` parameter to :func:`~django.forms.formsets.formset_factory`
111 gives you the ability to limit the number of forms the formset will display:
112
113 .. code-block:: pycon
114
115 >>> from django.forms import formset_factory
116 >>> from myapp.forms import ArticleForm
117 >>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
118 >>> formset = ArticleFormSet()
119 >>> for form in formset:
120 ... print(form)
121 ...
122 <div><label for="id_form-0-title">Title:</label><input type="text" name="form-0-title" id="id_form-0-title"></div>
123 <div><label for="id_form-0-pub_date">Pub date:</label><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></div>
124
125 If the value of ``max_num`` is greater than the number of existing items in the
126 initial data, up to ``extra`` additional blank forms will be added to the
127 formset, so long as the total number of forms does not exceed ``max_num``. For
128 example, if ``extra=2`` and ``max_num=2`` and the formset is initialized with
129 one ``initial`` item, a form for the initial item and one blank form will be
130 displayed.
131
132 If the number of items in the initial data exceeds ``max_num``, all initial
133 data forms will be displayed regardless of the value of ``max_num`` and no
134 extra forms will be displayed. For example, if ``extra=3`` and ``max_num=1``
135 and the formset is initialized with two initial items, two forms with the
136 initial data will be displayed.
137
138 A ``max_num`` value of ``None`` (the default) puts a high limit on the number
139 of forms displayed (1000). In practice this is equivalent to no limit.
140
141 By default, ``max_num`` only affects how many forms are displayed and does not
142 affect validation. If ``validate_max=True`` is passed to the
143 :func:`~django.forms.formsets.formset_factory`, then ``max_num`` will affect
144 validation. See :ref:`validate_max`.
145
146 .. _formsets-absolute-max:
147
148 Limiting the maximum number of instantiated forms
149 =================================================
150
151 The ``absolute_max`` parameter to :func:`.formset_factory` allows limiting the
152 number of forms that can be instantiated when supplying ``POST`` data. This
153 protects against memory exhaustion attacks using forged ``POST`` requests:
154
155 .. code-block:: pycon
156
157 >>> from django.forms.formsets import formset_factory
158 >>> from myapp.forms import ArticleForm
159 >>> ArticleFormSet = formset_factory(ArticleForm, absolute_max=1500)
160 >>> data = {
161 ... "form-TOTAL_FORMS": "1501",
162 ... "form-INITIAL_FORMS": "0",
163 ... }
164 >>> formset = ArticleFormSet(data)
165 >>> len(formset.forms)
166 1500
167 >>> formset.is_valid()
168 False
169 >>> formset.non_form_errors()
170 ['Please submit at most 1000 forms.']
171
172 When ``absolute_max`` is ``None``, it defaults to ``max_num + 1000``. (If
173 ``max_num`` is ``None``, it defaults to ``2000``).
174
175 If ``absolute_max`` is less than ``max_num``, a ``ValueError`` will be raised.
176
177 Formset validation
178 ==================
179
180 Validation with a formset is almost identical to a regular ``Form``. There is
181 an ``is_valid`` method on the formset to provide a convenient way to validate
182 all forms in the formset:
183
184 .. code-block:: pycon
185
186 >>> from django.forms import formset_factory
187 >>> from myapp.forms import ArticleForm
188 >>> ArticleFormSet = formset_factory(ArticleForm)
189 >>> data = {
190 ... "form-TOTAL_FORMS": "1",
191 ... "form-INITIAL_FORMS": "0",
192 ... }
193 >>> formset = ArticleFormSet(data)
194 >>> formset.is_valid()
195 True
196
197 We passed in no data to the formset which is resulting in a valid form. The
198 formset is smart enough to ignore extra forms that were not changed. If we
199 provide an invalid article:
200
201 .. code-block:: pycon
202
203 >>> data = {
204 ... "form-TOTAL_FORMS": "2",
205 ... "form-INITIAL_FORMS": "0",
206 ... "form-0-title": "Test",
207 ... "form-0-pub_date": "1904-06-16",
208 ... "form-1-title": "Test",
209 ... "form-1-pub_date": "", # <-- this date is missing but required
210 ... }
211 >>> formset = ArticleFormSet(data)
212 >>> formset.is_valid()
213 False
214 >>> formset.errors
215 [{}, {'pub_date': ['This field is required.']}]
216
217 As we can see, ``formset.errors`` is a list whose entries correspond to the
218 forms in the formset. Validation was performed for each of the two forms, and
219 the expected error message appears for the second item.
220
221 Just like when using a normal ``Form``, each field in a formset's forms may
222 include HTML attributes such as ``maxlength`` for browser validation. However,
223 form fields of formsets won't include the ``required`` attribute as that
224 validation may be incorrect when adding and deleting forms.
225
226 .. method:: BaseFormSet.total_error_count()
227
228 To check how many errors there are in the formset, we can use the
229 ``total_error_count`` method:
230
231 .. code-block:: pycon
232
233 >>> # Using the previous example
234 >>> formset.errors
235 [{}, {'pub_date': ['This field is required.']}]
236 >>> len(formset.errors)
237 2
238 >>> formset.total_error_count()
239 1
240
241 We can also check if form data differs from the initial data (i.e. the form was
242 sent without any data):
243
244 .. code-block:: pycon
245
246 >>> data = {
247 ... "form-TOTAL_FORMS": "1",
248 ... "form-INITIAL_FORMS": "0",
249 ... "form-0-title": "",
250 ... "form-0-pub_date": "",
251 ... }
252 >>> formset = ArticleFormSet(data)
253 >>> formset.has_changed()
254 False
255
256 .. _understanding-the-managementform:
257
258 Understanding the ``ManagementForm``
259 ------------------------------------
260
261 You may have noticed the additional data (``form-TOTAL_FORMS``,
262 ``form-INITIAL_FORMS``) that was required in the formset's data above. This
263 data is required for the ``ManagementForm``. This form is used by the formset
264 to manage the collection of forms contained in the formset. If you don't
265 provide this management data, the formset will be invalid:
266
267 .. code-block:: pycon
268
269 >>> data = {
270 ... "form-0-title": "Test",
271 ... "form-0-pub_date": "",
272 ... }
273 >>> formset = ArticleFormSet(data)
274 >>> formset.is_valid()
275 False
276
277 It is used to keep track of how many form instances are being displayed. If
278 you are adding new forms via JavaScript, you should increment the count fields
279 in this form as well. On the other hand, if you are using JavaScript to allow
280 deletion of existing objects, then you need to ensure the ones being removed
281 are properly marked for deletion by including ``form-#-DELETE`` in the ``POST``
282 data. It is expected that all forms are present in the ``POST`` data regardless.
283
284 The management form is available as an attribute of the formset
285 itself. When rendering a formset in a template, you can include all
286 the management data by rendering ``{{ my_formset.management_form }}``
287 (substituting the name of your formset as appropriate).
288
289 .. note::
290
291 As well as the ``form-TOTAL_FORMS`` and ``form-INITIAL_FORMS`` fields shown
292 in the examples here, the management form also includes
293 ``form-MIN_NUM_FORMS`` and ``form-MAX_NUM_FORMS`` fields. They are output
294 with the rest of the management form, but only for the convenience of
295 client-side code. These fields are not required and so are not shown in
296 the example ``POST`` data.
297
298 ``total_form_count`` and ``initial_form_count``
299 -----------------------------------------------
300
301 ``BaseFormSet`` has a couple of methods that are closely related to the
302 ``ManagementForm``, ``total_form_count`` and ``initial_form_count``.
303
304 ``total_form_count`` returns the total number of forms in this formset.
305 ``initial_form_count`` returns the number of forms in the formset that were
306 pre-filled, and is also used to determine how many forms are required. You
307 will probably never need to override either of these methods, so please be
308 sure you understand what they do before doing so.
309
310 .. _empty_form:
311
312 ``empty_form``
313 --------------
314
315 ``BaseFormSet`` provides an additional attribute ``empty_form`` which returns
316 a form instance with a prefix of ``__prefix__`` for easier use in dynamic
317 forms with JavaScript.
318
319 .. _formsets-error-messages:
320
321 ``error_messages``
322 ------------------
323
324 The ``error_messages`` argument lets you override the default messages that the
325 formset will raise. Pass in a dictionary with keys matching the error messages
326 you want to override. Error message keys include ``'too_few_forms'``,
327 ``'too_many_forms'``, and ``'missing_management_form'``. The
328 ``'too_few_forms'`` and ``'too_many_forms'`` error messages may contain
329 ``%(num)d``, which will be replaced with ``min_num`` and ``max_num``,
330 respectively.
331
332 For example, here is the default error message when the
333 management form is missing:
334
335 .. code-block:: pycon
336
337 >>> formset = ArticleFormSet({})
338 >>> formset.is_valid()
339 False
340 >>> formset.non_form_errors()
341 ['ManagementForm data is missing or has been tampered with. Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. You may need to file a bug report if the issue persists.']
342
343 And here is a custom error message:
344
345 .. code-block:: pycon
346
347 >>> formset = ArticleFormSet(
348 ... {}, error_messages={"missing_management_form": "Sorry, something went wrong."}
349 ... )
350 >>> formset.is_valid()
351 False
352 >>> formset.non_form_errors()
353 ['Sorry, something went wrong.']
354
355 Custom formset validation
356 -------------------------
357
358 A formset has a ``clean`` method similar to the one on a ``Form`` class. This
359 is where you define your own validation that works at the formset level:
360
361 .. code-block:: pycon
362
363 >>> from django.core.exceptions import ValidationError
364 >>> from django.forms import BaseFormSet
365 >>> from django.forms import formset_factory
366 >>> from myapp.forms import ArticleForm
367
368 >>> class BaseArticleFormSet(BaseFormSet):
369 ... def clean(self):
370 ... """Checks that no two articles have the same title."""
371 ... if any(self.errors):
372 ... # Don't bother validating the formset unless each form is valid on its own
373 ... return
374 ... titles = set()
375 ... for form in self.forms:
376 ... if self.can_delete and self._should_delete_form(form):
377 ... continue
378 ... title = form.cleaned_data.get("title")
379 ... if title in titles:
380 ... raise ValidationError("Articles in a set must have distinct titles.")
381 ... titles.add(title)
382 ...
383
384 >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
385 >>> data = {
386 ... "form-TOTAL_FORMS": "2",
387 ... "form-INITIAL_FORMS": "0",
388 ... "form-0-title": "Test",
389 ... "form-0-pub_date": "1904-06-16",
390 ... "form-1-title": "Test",
391 ... "form-1-pub_date": "1912-06-23",
392 ... }
393 >>> formset = ArticleFormSet(data)
394 >>> formset.is_valid()
395 False
396 >>> formset.errors
397 [{}, {}]
398 >>> formset.non_form_errors()
399 ['Articles in a set must have distinct titles.']
400
401 The formset ``clean`` method is called after all the ``Form.clean`` methods
402 have been called. The errors will be found using the ``non_form_errors()``
403 method on the formset.
404
405 Non-form errors will be rendered with an additional class of ``nonform`` to
406 help distinguish them from form-specific errors. For example,
407 ``{{ formset.non_form_errors }}`` would look like:
408
409 .. code-block:: html+django
410
411 <ul class="errorlist nonform">
412 <li>Articles in a set must have distinct titles.</li>
413 </ul>
414
415 Validating the number of forms in a formset
416 ===========================================
417
418 Django provides a couple ways to validate the minimum or maximum number of
419 submitted forms. Applications which need more customizable validation of the
420 number of forms should use custom formset validation.
421
422 .. _validate_max:
423
424 ``validate_max``
425 ----------------
426
427 If ``validate_max=True`` is passed to
428 :func:`~django.forms.formsets.formset_factory`, validation will also check
429 that the number of forms in the data set, minus those marked for
430 deletion, is less than or equal to ``max_num``.
431
432 .. code-block:: pycon
433
434 >>> from django.forms import formset_factory
435 >>> from myapp.forms import ArticleForm
436 >>> ArticleFormSet = formset_factory(ArticleForm, max_num=1, validate_max=True)
437 >>> data = {
438 ... "form-TOTAL_FORMS": "2",
439 ... "form-INITIAL_FORMS": "0",
440 ... "form-0-title": "Test",
441 ... "form-0-pub_date": "1904-06-16",
442 ... "form-1-title": "Test 2",
443 ... "form-1-pub_date": "1912-06-23",
444 ... }
445 >>> formset = ArticleFormSet(data)
446 >>> formset.is_valid()
447 False
448 >>> formset.errors
449 [{}, {}]
450 >>> formset.non_form_errors()
451 ['Please submit at most 1 form.']
452
453 ``validate_max=True`` validates against ``max_num`` strictly even if
454 ``max_num`` was exceeded because the amount of initial data supplied was
455 excessive.
456
457 The error message can be customized by passing the ``'too_many_forms'`` message
458 to the :ref:`formsets-error-messages` argument.
459
460 .. note::
461
462 Regardless of ``validate_max``, if the number of forms in a data set
463 exceeds ``absolute_max``, then the form will fail to validate as if
464 ``validate_max`` were set, and additionally only the first ``absolute_max``
465 forms will be validated. The remainder will be truncated entirely. This is
466 to protect against memory exhaustion attacks using forged POST requests.
467 See :ref:`formsets-absolute-max`.
468
469 ``validate_min``
470 ----------------
471
472 If ``validate_min=True`` is passed to
473 :func:`~django.forms.formsets.formset_factory`, validation will also check
474 that the number of forms in the data set, minus those marked for
475 deletion, is greater than or equal to ``min_num``.
476
477 .. code-block:: pycon
478
479 >>> from django.forms import formset_factory
480 >>> from myapp.forms import ArticleForm
481 >>> ArticleFormSet = formset_factory(ArticleForm, min_num=3, validate_min=True)
482 >>> data = {
483 ... "form-TOTAL_FORMS": "2",
484 ... "form-INITIAL_FORMS": "0",
485 ... "form-0-title": "Test",
486 ... "form-0-pub_date": "1904-06-16",
487 ... "form-1-title": "Test 2",
488 ... "form-1-pub_date": "1912-06-23",
489 ... }
490 >>> formset = ArticleFormSet(data)
491 >>> formset.is_valid()
492 False
493 >>> formset.errors
494 [{}, {}]
495 >>> formset.non_form_errors()
496 ['Please submit at least 3 forms.']
497
498 The error message can be customized by passing the ``'too_few_forms'`` message
499 to the :ref:`formsets-error-messages` argument.
500
501 .. note::
502
503 Regardless of ``validate_min``, if a formset contains no data, then
504 ``extra + min_num`` empty forms will be displayed.
505
506 Dealing with ordering and deletion of forms
507 ===========================================
508
509 The :func:`~django.forms.formsets.formset_factory` provides two optional
510 parameters ``can_order`` and ``can_delete`` to help with ordering of forms in
511 formsets and deletion of forms from a formset.
512
513 ``can_order``
514 -------------
515
516 .. attribute:: BaseFormSet.can_order
517
518 Default: ``False``
519
520 Lets you create a formset with the ability to order:
521
522 .. code-block:: pycon
523
524 >>> from django.forms import formset_factory
525 >>> from myapp.forms import ArticleForm
526 >>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)
527 >>> formset = ArticleFormSet(
528 ... initial=[
529 ... {"title": "Article #1", "pub_date": datetime.date(2008, 5, 10)},
530 ... {"title": "Article #2", "pub_date": datetime.date(2008, 5, 11)},
531 ... ]
532 ... )
533 >>> for form in formset:
534 ... print(form)
535 ...
536 <div><label for="id_form-0-title">Title:</label><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title"></div>
537 <div><label for="id_form-0-pub_date">Pub date:</label><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date"></div>
538 <div><label for="id_form-0-ORDER">Order:</label><input type="number" name="form-0-ORDER" value="1" id="id_form-0-ORDER"></div>
539 <div><label for="id_form-1-title">Title:</label><input type="text" name="form-1-title" value="Article #2" id="id_form-1-title"></div>
540 <div><label for="id_form-1-pub_date">Pub date:</label><input type="text" name="form-1-pub_date" value="2008-05-11" id="id_form-1-pub_date"></div>
541 <div><label for="id_form-1-ORDER">Order:</label><input type="number" name="form-1-ORDER" value="2" id="id_form-1-ORDER"></div>
542 <div><label for="id_form-2-title">Title:</label><input type="text" name="form-2-title" id="id_form-2-title"></div>
543 <div><label for="id_form-2-pub_date">Pub date:</label><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></div>
544 <div><label for="id_form-2-ORDER">Order:</label><input type="number" name="form-2-ORDER" id="id_form-2-ORDER"></div>
545
546 This adds an additional field to each form. This new field is named ``ORDER``
547 and is an ``forms.IntegerField``. For the forms that came from the initial
548 data it automatically assigned them a numeric value. Let's look at what will
549 happen when the user changes these values:
550
551 .. code-block:: pycon
552
553 >>> data = {
554 ... "form-TOTAL_FORMS": "3",
555 ... "form-INITIAL_FORMS": "2",
556 ... "form-0-title": "Article #1",
557 ... "form-0-pub_date": "2008-05-10",
558 ... "form-0-ORDER": "2",
559 ... "form-1-title": "Article #2",
560 ... "form-1-pub_date": "2008-05-11",
561 ... "form-1-ORDER": "1",
562 ... "form-2-title": "Article #3",
563 ... "form-2-pub_date": "2008-05-01",
564 ... "form-2-ORDER": "0",
565 ... }
566
567 >>> formset = ArticleFormSet(
568 ... data,
569 ... initial=[
570 ... {"title": "Article #1", "pub_date": datetime.date(2008, 5, 10)},
571 ... {"title": "Article #2", "pub_date": datetime.date(2008, 5, 11)},
572 ... ],
573 ... )
574 >>> for form in formset.ordered_forms:
575 ... print(form.cleaned_data)
576 ...
577 {'title': 'Article #3', 'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0}
578 {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1}
579 {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2}
580
581 :class:`~django.forms.formsets.BaseFormSet` also provides an
582 :attr:`~django.forms.formsets.BaseFormSet.ordering_widget` attribute and
583 :meth:`~django.forms.formsets.BaseFormSet.get_ordering_widget` method that
584 control the widget used with
585 :attr:`~django.forms.formsets.BaseFormSet.can_order`.
586
587 ``ordering_widget``
588 ^^^^^^^^^^^^^^^^^^^
589
590 .. attribute:: BaseFormSet.ordering_widget
591
592 Default: :class:`~django.forms.NumberInput`
593
594 Set ``ordering_widget`` to specify the widget class to be used with
595 ``can_order``:
596
597 .. code-block:: pycon
598
599 >>> from django.forms import BaseFormSet, formset_factory
600 >>> from myapp.forms import ArticleForm
601 >>> class BaseArticleFormSet(BaseFormSet):
602 ... ordering_widget = HiddenInput
603 ...
604
605 >>> ArticleFormSet = formset_factory(
606 ... ArticleForm, formset=BaseArticleFormSet, can_order=True
607 ... )
608
609 ``get_ordering_widget``
610 ^^^^^^^^^^^^^^^^^^^^^^^
611
612 .. method:: BaseFormSet.get_ordering_widget()
613
614 Override ``get_ordering_widget()`` if you need to provide a widget instance for
615 use with ``can_order``:
616
617 .. code-block:: pycon
618
619 >>> from django.forms import BaseFormSet, formset_factory
620 >>> from myapp.forms import ArticleForm
621 >>> class BaseArticleFormSet(BaseFormSet):
622 ... def get_ordering_widget(self):
623 ... return HiddenInput(attrs={"class": "ordering"})
624 ...
625
626 >>> ArticleFormSet = formset_factory(
627 ... ArticleForm, formset=BaseArticleFormSet, can_order=True
628 ... )
629
630 ``can_delete``
631 --------------
632
633 .. attribute:: BaseFormSet.can_delete
634
635 Default: ``False``
636
637 Lets you create a formset with the ability to select forms for deletion:
638
639 .. code-block:: pycon
640
641 >>> from django.forms import formset_factory
642 >>> from myapp.forms import ArticleForm
643 >>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True)
644 >>> formset = ArticleFormSet(
645 ... initial=[
646 ... {"title": "Article #1", "pub_date": datetime.date(2008, 5, 10)},
647 ... {"title": "Article #2", "pub_date": datetime.date(2008, 5, 11)},
648 ... ]
649 ... )
650 >>> for form in formset:
651 ... print(form)
652 ...
653 <div><label for="id_form-0-title">Title:</label><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title"></div>
654 <div><label for="id_form-0-pub_date">Pub date:</label><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date"></div>
655 <div><label for="id_form-0-DELETE">Delete:</label><input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE"></div>
656 <div><label for="id_form-1-title">Title:</label><input type="text" name="form-1-title" value="Article #2" id="id_form-1-title"></div>
657 <div><label for="id_form-1-pub_date">Pub date:</label><input type="text" name="form-1-pub_date" value="2008-05-11" id="id_form-1-pub_date"></div>
658 <div><label for="id_form-1-DELETE">Delete:</label><input type="checkbox" name="form-1-DELETE" id="id_form-1-DELETE"></div>
659 <div><label for="id_form-2-title">Title:</label><input type="text" name="form-2-title" id="id_form-2-title"></div>
660 <div><label for="id_form-2-pub_date">Pub date:</label><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></div>
661 <div><label for="id_form-2-DELETE">Delete:</label><input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE"></div>
662
663 Similar to ``can_order`` this adds a new field to each form named ``DELETE``
664 and is a ``forms.BooleanField``. When data comes through marking any of the
665 delete fields you can access them with ``deleted_forms``:
666
667 .. code-block:: pycon
668
669 >>> data = {
670 ... "form-TOTAL_FORMS": "3",
671 ... "form-INITIAL_FORMS": "2",
672 ... "form-0-title": "Article #1",
673 ... "form-0-pub_date": "2008-05-10",
674 ... "form-0-DELETE": "on",
675 ... "form-1-title": "Article #2",
676 ... "form-1-pub_date": "2008-05-11",
677 ... "form-1-DELETE": "",
678 ... "form-2-title": "",
679 ... "form-2-pub_date": "",
680 ... "form-2-DELETE": "",
681 ... }
682
683 >>> formset = ArticleFormSet(
684 ... data,
685 ... initial=[
686 ... {"title": "Article #1", "pub_date": datetime.date(2008, 5, 10)},
687 ... {"title": "Article #2", "pub_date": datetime.date(2008, 5, 11)},
688 ... ],
689 ... )
690 >>> [form.cleaned_data for form in formset.deleted_forms]
691 [{'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10), 'DELETE': True}]
692
693 If you are using a :class:`ModelFormSet<django.forms.models.BaseModelFormSet>`,
694 model instances for deleted forms will be deleted when you call
695 ``formset.save()``.
696
697 If you call ``formset.save(commit=False)``, objects will not be deleted
698 automatically. You'll need to call ``delete()`` on each of the
699 :attr:`formset.deleted_objects
700 <django.forms.models.BaseModelFormSet.deleted_objects>` to actually delete
701 them:
702
703 .. code-block:: pycon
704
705 >>> instances = formset.save(commit=False)
706 >>> for obj in formset.deleted_objects:
707 ... obj.delete()
708 ...
709
710 On the other hand, if you are using a plain ``FormSet``, it's up to you to
711 handle ``formset.deleted_forms``, perhaps in your formset's ``save()`` method,
712 as there's no general notion of what it means to delete a form.
713
714 :class:`~django.forms.formsets.BaseFormSet` also provides a
715 :attr:`~django.forms.formsets.BaseFormSet.deletion_widget` attribute and
716 :meth:`~django.forms.formsets.BaseFormSet.get_deletion_widget` method that
717 control the widget used with
718 :attr:`~django.forms.formsets.BaseFormSet.can_delete`.
719
720 ``deletion_widget``
721 ^^^^^^^^^^^^^^^^^^^
722
723 .. attribute:: BaseFormSet.deletion_widget
724
725 Default: :class:`~django.forms.CheckboxInput`
726
727 Set ``deletion_widget`` to specify the widget class to be used with
728 ``can_delete``:
729
730 .. code-block:: pycon
731
732 >>> from django.forms import BaseFormSet, formset_factory
733 >>> from myapp.forms import ArticleForm
734 >>> class BaseArticleFormSet(BaseFormSet):
735 ... deletion_widget = HiddenInput
736 ...
737
738 >>> ArticleFormSet = formset_factory(
739 ... ArticleForm, formset=BaseArticleFormSet, can_delete=True
740 ... )
741
742 ``get_deletion_widget``
743 ^^^^^^^^^^^^^^^^^^^^^^^
744
745 .. method:: BaseFormSet.get_deletion_widget()
746
747 Override ``get_deletion_widget()`` if you need to provide a widget instance for
748 use with ``can_delete``:
749
750 .. code-block:: pycon
751
752 >>> from django.forms import BaseFormSet, formset_factory
753 >>> from myapp.forms import ArticleForm
754 >>> class BaseArticleFormSet(BaseFormSet):
755 ... def get_deletion_widget(self):
756 ... return HiddenInput(attrs={"class": "deletion"})
757 ...
758
759 >>> ArticleFormSet = formset_factory(
760 ... ArticleForm, formset=BaseArticleFormSet, can_delete=True
761 ... )
762
763 ``can_delete_extra``
764 --------------------
765
766 .. attribute:: BaseFormSet.can_delete_extra
767
768 Default: ``True``
769
770 While setting ``can_delete=True``, specifying ``can_delete_extra=False`` will
771 remove the option to delete extra forms.
772
773 Adding additional fields to a formset
774 =====================================
775
776 If you need to add additional fields to the formset this can be easily
777 accomplished. The formset base class provides an ``add_fields`` method. You
778 can override this method to add your own fields or even redefine the default
779 fields/attributes of the order and deletion fields:
780
781 .. code-block:: pycon
782
783 >>> from django.forms import BaseFormSet
784 >>> from django.forms import formset_factory
785 >>> from myapp.forms import ArticleForm
786 >>> class BaseArticleFormSet(BaseFormSet):
787 ... def add_fields(self, form, index):
788 ... super().add_fields(form, index)
789 ... form.fields["my_field"] = forms.CharField()
790 ...
791
792 >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
793 >>> formset = ArticleFormSet()
794 >>> for form in formset:
795 ... print(form)
796 ...
797 <div><label for="id_form-0-title">Title:</label><input type="text" name="form-0-title" id="id_form-0-title"></div>
798 <div><label for="id_form-0-pub_date">Pub date:</label><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></div>
799 <div><label for="id_form-0-my_field">My field:</label><input type="text" name="form-0-my_field" id="id_form-0-my_field"></div>
800
801 .. _custom-formset-form-kwargs:
802
803 Passing custom parameters to formset forms
804 ==========================================
805
806 Sometimes your form class takes custom parameters, like ``MyArticleForm``.
807 You can pass this parameter when instantiating the formset:
808
809 .. code-block:: pycon
810
811 >>> from django.forms import BaseFormSet
812 >>> from django.forms import formset_factory
813 >>> from myapp.forms import ArticleForm
814
815 >>> class MyArticleForm(ArticleForm):
816 ... def __init__(self, *args, user, **kwargs):
817 ... self.user = user
818 ... super().__init__(*args, **kwargs)
819 ...
820
821 >>> ArticleFormSet = formset_factory(MyArticleForm)
822 >>> formset = ArticleFormSet(form_kwargs={"user": request.user})
823
824 The ``form_kwargs`` may also depend on the specific form instance. The formset
825 base class provides a ``get_form_kwargs`` method. The method takes a single
826 argument - the index of the form in the formset. The index is ``None`` for the
827 :ref:`empty_form`:
828
829 .. code-block:: pycon
830
831 >>> from django.forms import BaseFormSet
832 >>> from django.forms import formset_factory
833
834 >>> class BaseArticleFormSet(BaseFormSet):
835 ... def get_form_kwargs(self, index):
836 ... kwargs = super().get_form_kwargs(index)
837 ... kwargs["custom_kwarg"] = index
838 ... return kwargs
839 ...
840
841 >>> ArticleFormSet = formset_factory(MyArticleForm, formset=BaseArticleFormSet)
842 >>> formset = ArticleFormSet()
843
844 .. _formset-prefix:
845
846 Customizing a formset's prefix
847 ==============================
848
849 In the rendered HTML, formsets include a prefix on each field's name. By
850 default, the prefix is ``'form'``, but it can be customized using the formset's
851 ``prefix`` argument.
852
853 For example, in the default case, you might see:
854
855 .. code-block:: html
856
857 <label for="id_form-0-title">Title:</label>
858 <input type="text" name="form-0-title" id="id_form-0-title">
859
860 But with ``ArticleFormset(prefix='article')`` that becomes:
861
862 .. code-block:: html
863
864 <label for="id_article-0-title">Title:</label>
865 <input type="text" name="article-0-title" id="id_article-0-title">
866
867 This is useful if you want to :ref:`use more than one formset in a view
868 <multiple-formsets-in-view>`.
869
870 .. _formset-rendering:
871
872 Using a formset in views and templates
873 ======================================
874
875 Formsets have the following attributes and methods associated with rendering:
876
877 .. attribute:: BaseFormSet.renderer
878
879 Specifies the :doc:`renderer </ref/forms/renderers>` to use for the
880 formset. Defaults to the renderer specified by the :setting:`FORM_RENDERER`
881 setting.
882
883 .. attribute:: BaseFormSet.template_name
884
885 The name of the template rendered if the formset is cast into a string,
886 e.g. via ``print(formset)`` or in a template via ``{{ formset }}``.
887
888 By default, a property returning the value of the renderer's
889 :attr:`~django.forms.renderers.BaseRenderer.formset_template_name`. You may
890 set it as a string template name in order to override that for a particular
891 formset class.
892
893 This template will be used to render the formset's management form, and
894 then each form in the formset as per the template defined by the form's
895 :attr:`~django.forms.Form.template_name`.
896
897 .. attribute:: BaseFormSet.template_name_div
898
899 The name of the template used when calling :meth:`.as_div`. By default this
900 is ``"django/forms/formsets/div.html"``. This template renders the
901 formset's management form and then each form in the formset as per the
902 form's :meth:`~django.forms.Form.as_div` method.
903
904 .. attribute:: BaseFormSet.template_name_p
905
906 The name of the template used when calling :meth:`.as_p`. By default this
907 is ``"django/forms/formsets/p.html"``. This template renders the formset's
908 management form and then each form in the formset as per the form's
909 :meth:`~django.forms.Form.as_p` method.
910
911 .. attribute:: BaseFormSet.template_name_table
912
913 The name of the template used when calling :meth:`.as_table`. By default
914 this is ``"django/forms/formsets/table.html"``. This template renders the
915 formset's management form and then each form in the formset as per the
916 form's :meth:`~django.forms.Form.as_table` method.
917
918 .. attribute:: BaseFormSet.template_name_ul
919
920 The name of the template used when calling :meth:`.as_ul`. By default this
921 is ``"django/forms/formsets/ul.html"``. This template renders the formset's
922 management form and then each form in the formset as per the form's
923 :meth:`~django.forms.Form.as_ul` method.
924
925 .. method:: BaseFormSet.get_context()
926
927 Returns the context for rendering a formset in a template.
928
929 The available context is:
930
931 * ``formset`` : The instance of the formset.
932
933 .. method:: BaseFormSet.render(template_name=None, context=None, renderer=None)
934
935 The render method is called by ``__str__`` as well as the :meth:`.as_div`,
936 :meth:`.as_p`, :meth:`.as_ul`, and :meth:`.as_table` methods. All arguments
937 are optional and will default to:
938
939 * ``template_name``: :attr:`.template_name`
940 * ``context``: Value returned by :meth:`.get_context`
941 * ``renderer``: Value returned by :attr:`.renderer`
942
943 .. method:: BaseFormSet.as_div()
944
945 Renders the formset with the :attr:`.template_name_div` template.
946
947 .. method:: BaseFormSet.as_p()
948
949 Renders the formset with the :attr:`.template_name_p` template.
950
951 .. method:: BaseFormSet.as_table()
952
953 Renders the formset with the :attr:`.template_name_table` template.
954
955 .. method:: BaseFormSet.as_ul()
956
957 Renders the formset with the :attr:`.template_name_ul` template.
958
959 Using a formset inside a view is not very different from using a regular
960 ``Form`` class. The only thing you will want to be aware of is making sure to
961 use the management form inside the template. Let's look at a sample view::
962
963 from django.forms import formset_factory
964 from django.shortcuts import render
965 from myapp.forms import ArticleForm
966
967
968 def manage_articles(request):
969 ArticleFormSet = formset_factory(ArticleForm)
970 if request.method == "POST":
971 formset = ArticleFormSet(request.POST, request.FILES)
972 if formset.is_valid():
973 # do something with the formset.cleaned_data
974 pass
975 else:
976 formset = ArticleFormSet()
977 return render(request, "manage_articles.html", {"formset": formset})
978
979 The ``manage_articles.html`` template might look like this:
980
981 .. code-block:: html+django
982
983 <form method="post">
984 {{ formset.management_form }}
985 <table>
986 {% for form in formset %}
987 {{ form }}
988 {% endfor %}
989 </table>
990 </form>
991
992 However there's a slight shortcut for the above by letting the formset itself
993 deal with the management form:
994
995 .. code-block:: html+django
996
997 <form method="post">
998 <table>
999 {{ formset }}
1000 </table>
1001 </form>
1002
1003 The above ends up calling the :meth:`BaseFormSet.render` method on the formset
1004 class. This renders the formset using the template specified by the
1005 :attr:`~BaseFormSet.template_name` attribute. Similar to forms, by default the
1006 formset will be rendered ``as_div``, with other helper methods of ``as_p``,
1007 ``as_ul``, and ``as_table`` being available. The rendering of the formset can
1008 be customized by specifying the ``template_name`` attribute, or more generally
1009 by :ref:`overriding the default template
1010 <overriding-built-in-formset-templates>`.
1011
1012 .. _manually-rendered-can-delete-and-can-order:
1013
1014 Manually rendered ``can_delete`` and ``can_order``
1015 --------------------------------------------------
1016
1017 If you manually render fields in the template, you can render
1018 ``can_delete`` parameter with ``{{ form.DELETE }}``:
1019
1020 .. code-block:: html+django
1021
1022 <form method="post">
1023 {{ formset.management_form }}
1024 {% for form in formset %}
1025 <ul>
1026 <li>{{ form.title }}</li>
1027 <li>{{ form.pub_date }}</li>
1028 {% if formset.can_delete %}
1029 <li>{{ form.DELETE }}</li>
1030 {% endif %}
1031 </ul>
1032 {% endfor %}
1033 </form>
1034
1035
1036 Similarly, if the formset has the ability to order (``can_order=True``), it is
1037 possible to render it with ``{{ form.ORDER }}``.
1038
1039 .. _multiple-formsets-in-view:
1040
1041 Using more than one formset in a view
1042 -------------------------------------
1043
1044 You are able to use more than one formset in a view if you like. Formsets
1045 borrow much of its behavior from forms. With that said you are able to use
1046 ``prefix`` to prefix formset form field names with a given value to allow
1047 more than one formset to be sent to a view without name clashing. Let's take
1048 a look at how this might be accomplished::
1049
1050 from django.forms import formset_factory
1051 from django.shortcuts import render
1052 from myapp.forms import ArticleForm, BookForm
1053
1054
1055 def manage_articles(request):
1056 ArticleFormSet = formset_factory(ArticleForm)
1057 BookFormSet = formset_factory(BookForm)
1058 if request.method == "POST":
1059 article_formset = ArticleFormSet(request.POST, request.FILES, prefix="articles")
1060 book_formset = BookFormSet(request.POST, request.FILES, prefix="books")
1061 if article_formset.is_valid() and book_formset.is_valid():
1062 # do something with the cleaned_data on the formsets.
1063 pass
1064 else:
1065 article_formset = ArticleFormSet(prefix="articles")
1066 book_formset = BookFormSet(prefix="books")
1067 return render(
1068 request,
1069 "manage_articles.html",
1070 {
1071 "article_formset": article_formset,
1072 "book_formset": book_formset,
1073 },
1074 )
1075
1076 You would then render the formsets as normal. It is important to point out
1077 that you need to pass ``prefix`` on both the POST and non-POST cases so that
1078 it is rendered and processed correctly.
1079
1080 Each formset's :ref:`prefix <formset-prefix>` replaces the default ``form``
1081 prefix that's added to each field's ``name`` and ``id`` HTML attributes.