Formsets

    A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid. Let’s say you have the following form:

    You might want to allow the user to create several articles at once. To create a formset out of an ArticleForm you would do:

    1. >>> from django.forms import formset_factory
    2. >>> ArticleFormSet = formset_factory(ArticleForm)

    You now have created a formset class named ArticleFormSet. Instantiating the formset gives you the ability to iterate over the forms in the formset and display them as you would with a regular form:

    1. >>> formset = ArticleFormSet()
    2. >>> for form in formset:
    3. ... print(form.as_table())
    4. <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>
    5. <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>

    As you can see it only displayed one empty form. The number of empty forms that is displayed is controlled by the extra parameter. By default, formset_factory() defines one extra form; the following example will create a formset class to display two blank forms:

    1. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)

    Iterating over a formset will render the forms in the order they were created. You can change this order by providing an alternate implementation for the __iter__() method.

    Formsets can also be indexed into, which returns the corresponding form. If you override __iter__, you will need to also override __getitem__ to have matching behavior.

    Initial data is what drives the main usability of a formset. As shown above you can define the number of extra forms. What this means is that you are telling the formset how many additional forms to show in addition to the number of forms it generates from the initial data. Let’s take a look at an example:

    1. >>> import datetime
    2. >>> from django.forms import formset_factory
    3. >>> from myapp.forms import ArticleForm
    4. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
    5. >>> formset = ArticleFormSet(initial=[
    6. ... {'title': 'Django is now open source',
    7. ... 'pub_date': datetime.date.today(),}
    8. ... ])
    9. >>> for form in formset:
    10. ... print(form.as_table())
    11. <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>
    12. <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>
    13. <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>
    14. <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>
    15. <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>
    16. <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>

    There are now a total of three forms showing above. One for the initial data that was passed in and two extra forms. Also note that we are passing in a list of dictionaries as the initial data.

    If you use an initial for displaying a formset, you should pass the same initial when processing that formset’s submission so that the formset can detect which forms were changed by the user. For example, you might have something like: ArticleFormSet(request.POST, initial=[...]).

    See also

    .

    Limiting the maximum number of forms

    The max_num parameter to gives you the ability to limit the number of forms the formset will display:

    1. >>> from django.forms import formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
    4. >>> formset = ArticleFormSet()
    5. >>> for form in formset:
    6. ... print(form.as_table())
    7. <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>
    8. <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>

    If the value of max_num is greater than the number of existing items in the initial data, up to extra additional blank forms will be added to the formset, so long as the total number of forms does not exceed max_num. For example, if extra=2 and max_num=2 and the formset is initialized with one initial item, a form for the initial item and one blank form will be displayed.

    If the number of items in the initial data exceeds max_num, all initial data forms will be displayed regardless of the value of max_num and no extra forms will be displayed. For example, if extra=3 and max_num=1 and the formset is initialized with two initial items, two forms with the initial data will be displayed.

    A max_num value of None (the default) puts a high limit on the number of forms displayed (1000). In practice this is equivalent to no limit.

    By default, max_num only affects how many forms are displayed and does not affect validation. If validate_max=True is passed to the formset_factory(), then max_num will affect validation. See .

    Limiting the maximum number of instantiated forms

    New in Django 3.2.

    The absolute_max parameter to allows limiting the number of forms that can be instantiated when supplying POST data. This protects against memory exhaustion attacks using forged POST requests:

    1. >>> from django.forms.formsets import formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> ArticleFormSet = formset_factory(ArticleForm, absolute_max=1500)
    4. >>> data = {
    5. ... 'form-TOTAL_FORMS': '1501',
    6. ... 'form-INITIAL_FORMS': '0',
    7. ... }
    8. >>> formset = ArticleFormSet(data)
    9. >>> len(formset.forms)
    10. 1500
    11. >>> formset.is_valid()
    12. False
    13. >>> formset.non_form_errors()
    14. ['Please submit at most 1000 forms.']

    When absolute_max is None, it defaults to max_num + 1000. (If max_num is None, it defaults to 2000).

    If absolute_max is less than max_num, a ValueError will be raised.

    Validation with a formset is almost identical to a regular Form. There is an is_valid method on the formset to provide a convenient way to validate all forms in the formset:

    1. >>> from django.forms import formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> ArticleFormSet = formset_factory(ArticleForm)
    4. >>> data = {
    5. ... 'form-TOTAL_FORMS': '1',
    6. ... 'form-INITIAL_FORMS': '0',
    7. ... }
    8. >>> formset = ArticleFormSet(data)
    9. >>> formset.is_valid()
    10. True

    We passed in no data to the formset which is resulting in a valid form. The formset is smart enough to ignore extra forms that were not changed. If we provide an invalid article:

    1. >>> data = {
    2. ... 'form-TOTAL_FORMS': '2',
    3. ... 'form-INITIAL_FORMS': '0',
    4. ... 'form-0-title': 'Test',
    5. ... 'form-0-pub_date': '1904-06-16',
    6. ... 'form-1-title': 'Test',
    7. ... 'form-1-pub_date': '', # <-- this date is missing but required
    8. ... }
    9. >>> formset = ArticleFormSet(data)
    10. >>> formset.is_valid()
    11. False
    12. >>> formset.errors
    13. [{}, {'pub_date': ['This field is required.']}]

    As we can see, formset.errors is a list whose entries correspond to the forms in the formset. Validation was performed for each of the two forms, and the expected error message appears for the second item.

    Just like when using a normal Form, each field in a formset’s forms may include HTML attributes such as maxlength for browser validation. However, form fields of formsets won’t include the required attribute as that validation may be incorrect when adding and deleting forms.

    BaseFormSet.``total_error_count()

    To check how many errors there are in the formset, we can use the total_error_count method:

    1. >>> # Using the previous example
    2. >>> formset.errors
    3. [{}, {'pub_date': ['This field is required.']}]
    4. >>> len(formset.errors)
    5. 2
    6. >>> formset.total_error_count()
    7. 1

    We can also check if form data differs from the initial data (i.e. the form was sent without any data):

    1. >>> data = {
    2. ... 'form-TOTAL_FORMS': '1',
    3. ... 'form-INITIAL_FORMS': '0',
    4. ... 'form-0-title': '',
    5. ... 'form-0-pub_date': '',
    6. ... }
    7. >>> formset = ArticleFormSet(data)
    8. >>> formset.has_changed()
    9. False

    You may have noticed the additional data (form-TOTAL_FORMS, form-INITIAL_FORMS) that was required in the formset’s data above. This data is required for the ManagementForm. This form is used by the formset to manage the collection of forms contained in the formset. If you don’t provide this management data, the formset will be invalid:

    1. >>> data = {
    2. ... 'form-0-title': 'Test',
    3. ... 'form-0-pub_date': '',
    4. ... }
    5. >>> formset = ArticleFormSet(data)
    6. >>> formset.is_valid()
    7. False

    It is used to keep track of how many form instances are being displayed. If you are adding new forms via JavaScript, you should increment the count fields in this form as well. On the other hand, if you are using JavaScript to allow deletion of existing objects, then you need to ensure the ones being removed are properly marked for deletion by including form-#-DELETE in the POST data. It is expected that all forms are present in the POST data regardless.

    The management form is available as an attribute of the formset itself. When rendering a formset in a template, you can include all the management data by rendering {{ my_formset.management_form }} (substituting the name of your formset as appropriate).

    Note

    As well as the form-TOTAL_FORMS and form-INITIAL_FORMS fields shown in the examples here, the management form also includes form-MIN_NUM_FORMS and form-MAX_NUM_FORMS fields. They are output with the rest of the management form, but only for the convenience of client-side code. These fields are not required and so are not shown in the example POST data.

    Changed in Django 3.2:

    formset.is_valid() now returns False rather than raising an exception when the management form is missing or has been tampered with.

    total_form_count and initial_form_count

    BaseFormSet has a couple of methods that are closely related to the ManagementForm, total_form_count and initial_form_count.

    total_form_count returns the total number of forms in this formset. initial_form_count returns the number of forms in the formset that were pre-filled, and is also used to determine how many forms are required. You will probably never need to override either of these methods, so please be sure you understand what they do before doing so.

    empty_form

    BaseFormSet provides an additional attribute empty_form which returns a form instance with a prefix of __prefix__ for easier use in dynamic forms with JavaScript.

    error_messages

    New in Django 3.2.

    The error_messages argument lets you override the default messages that the formset will raise. Pass in a dictionary with keys matching the error messages you want to override. For example, here is the default error message when the management form is missing:

    And here is a custom error message:

    1. >>> formset = ArticleFormSet({}, error_messages={'missing_management_form': 'Sorry, something went wrong.'})
    2. >>> formset.is_valid()
    3. False
    4. >>> formset.non_form_errors()
    5. ['Sorry, something went wrong.']

    A formset has a clean method similar to the one on a Form class. This is where you define your own validation that works at the formset level:

    1. >>> from django.core.exceptions import ValidationError
    2. >>> from django.forms import BaseFormSet
    3. >>> from django.forms import formset_factory
    4. >>> class BaseArticleFormSet(BaseFormSet):
    5. ... def clean(self):
    6. ... """Checks that no two articles have the same title."""
    7. ... if any(self.errors):
    8. ... # Don't bother validating the formset unless each form is valid on its own
    9. ... return
    10. ... titles = []
    11. ... for form in self.forms:
    12. ... if self.can_delete and self._should_delete_form(form):
    13. ... continue
    14. ... title = form.cleaned_data.get('title')
    15. ... if title in titles:
    16. ... raise ValidationError("Articles in a set must have distinct titles.")
    17. ... titles.append(title)
    18. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
    19. >>> data = {
    20. ... 'form-TOTAL_FORMS': '2',
    21. ... 'form-INITIAL_FORMS': '0',
    22. ... 'form-0-title': 'Test',
    23. ... 'form-0-pub_date': '1904-06-16',
    24. ... 'form-1-title': 'Test',
    25. ... 'form-1-pub_date': '1912-06-23',
    26. ... }
    27. >>> formset = ArticleFormSet(data)
    28. >>> formset.is_valid()
    29. False
    30. >>> formset.errors
    31. [{}, {}]
    32. >>> formset.non_form_errors()
    33. ['Articles in a set must have distinct titles.']

    The formset clean method is called after all the Form.clean methods have been called. The errors will be found using the non_form_errors() method on the formset.

    1. <ul class="errorlist nonform">
    2. <li>Articles in a set must have distinct titles.</li>
    3. </ul>

    Changed in Django 4.0:

    The additional nonform class was added.

    Validating the number of forms in a formset

    Django provides a couple ways to validate the minimum or maximum number of submitted forms. Applications which need more customizable validation of the number of forms should use custom formset validation.

    validate_max

    If validate_max=True is passed to , validation will also check that the number of forms in the data set, minus those marked for deletion, is less than or equal to max_num.

    1. >>> from django.forms import formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> ArticleFormSet = formset_factory(ArticleForm, max_num=1, validate_max=True)
    4. >>> data = {
    5. ... 'form-TOTAL_FORMS': '2',
    6. ... 'form-INITIAL_FORMS': '0',
    7. ... 'form-0-title': 'Test',
    8. ... 'form-0-pub_date': '1904-06-16',
    9. ... 'form-1-title': 'Test 2',
    10. ... 'form-1-pub_date': '1912-06-23',
    11. ... }
    12. >>> formset = ArticleFormSet(data)
    13. >>> formset.is_valid()
    14. False
    15. >>> formset.errors
    16. [{}, {}]
    17. >>> formset.non_form_errors()
    18. ['Please submit at most 1 form.']

    validate_max=True validates against max_num strictly even if max_num was exceeded because the amount of initial data supplied was excessive.

    Note

    Regardless of validate_max, if the number of forms in a data set exceeds absolute_max, then the form will fail to validate as if validate_max were set, and additionally only the first absolute_max forms will be validated. The remainder will be truncated entirely. This is to protect against memory exhaustion attacks using forged POST requests. See Limiting the maximum number of instantiated forms.

    validate_min

    If validate_min=True is passed to formset_factory(), validation will also check that the number of forms in the data set, minus those marked for deletion, is greater than or equal to min_num.

    1. >>> from django.forms import formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> ArticleFormSet = formset_factory(ArticleForm, min_num=3, validate_min=True)
    4. >>> data = {
    5. ... 'form-TOTAL_FORMS': '2',
    6. ... 'form-INITIAL_FORMS': '0',
    7. ... 'form-0-title': 'Test',
    8. ... 'form-0-pub_date': '1904-06-16',
    9. ... 'form-1-title': 'Test 2',
    10. ... 'form-1-pub_date': '1912-06-23',
    11. ... }
    12. >>> formset = ArticleFormSet(data)
    13. >>> formset.is_valid()
    14. False
    15. >>> formset.errors
    16. [{}, {}]
    17. >>> formset.non_form_errors()
    18. ['Please submit at least 3 forms.']

    Note

    Regardless of validate_min, if a formset contains no data, then extra + min_num empty forms will be displayed.

    Dealing with ordering and deletion of forms

    The formset_factory() provides two optional parameters can_order and can_delete to help with ordering of forms in formsets and deletion of forms from a formset.

    can_order

    BaseFormSet.``can_order

    Default: False

    Lets you create a formset with the ability to order:

    1. >>> from django.forms import formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)
    4. >>> formset = ArticleFormSet(initial=[
    5. ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
    6. ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
    7. ... ])
    8. >>> for form in formset:
    9. ... print(form.as_table())
    10. <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>
    11. <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>
    12. <tr><th><label for="id_form-0-ORDER">Order:</label></th><td><input type="number" name="form-0-ORDER" value="1" id="id_form-0-ORDER"></td></tr>
    13. <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>
    14. <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>
    15. <tr><th><label for="id_form-1-ORDER">Order:</label></th><td><input type="number" name="form-1-ORDER" value="2" id="id_form-1-ORDER"></td></tr>
    16. <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>
    17. <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>
    18. <tr><th><label for="id_form-2-ORDER">Order:</label></th><td><input type="number" name="form-2-ORDER" id="id_form-2-ORDER"></td></tr>

    This adds an additional field to each form. This new field is named ORDER and is an forms.IntegerField. For the forms that came from the initial data it automatically assigned them a numeric value. Let’s look at what will happen when the user changes these values:

    1. >>> data = {
    2. ... 'form-TOTAL_FORMS': '3',
    3. ... 'form-INITIAL_FORMS': '2',
    4. ... 'form-0-title': 'Article #1',
    5. ... 'form-0-pub_date': '2008-05-10',
    6. ... 'form-0-ORDER': '2',
    7. ... 'form-1-title': 'Article #2',
    8. ... 'form-1-pub_date': '2008-05-11',
    9. ... 'form-1-ORDER': '1',
    10. ... 'form-2-title': 'Article #3',
    11. ... 'form-2-pub_date': '2008-05-01',
    12. ... 'form-2-ORDER': '0',
    13. ... }
    14. >>> formset = ArticleFormSet(data, initial=[
    15. ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
    16. ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
    17. ... ])
    18. >>> formset.is_valid()
    19. True
    20. >>> for form in formset.ordered_forms:
    21. ... print(form.cleaned_data)
    22. {'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': 'Article #3'}
    23. {'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': 'Article #2'}
    24. {'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': 'Article #1'}

    BaseFormSet also provides an attribute and get_ordering_widget() method that control the widget used with .

    ordering_widget

    BaseFormSet.``ordering_widget

    Default:

    Set ordering_widget to specify the widget class to be used with can_order:

    1. >>> from django.forms import BaseFormSet, formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> class BaseArticleFormSet(BaseFormSet):
    4. ... ordering_widget = HiddenInput
    5. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)

    get_ordering_widget

    BaseFormSet.``get_ordering_widget()

    Override get_ordering_widget() if you need to provide a widget instance for use with can_order:

    1. >>> from django.forms import BaseFormSet, formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> class BaseArticleFormSet(BaseFormSet):
    4. ... def get_ordering_widget(self):
    5. ... return HiddenInput(attrs={'class': 'ordering'})
    6. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)

    BaseFormSet.``can_delete

    Default: False

    Lets you create a formset with the ability to select forms for deletion:

    1. >>> from django.forms import formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> formset = ArticleFormSet(initial=[
    4. ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
    5. ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
    6. ... ])
    7. >>> for form in formset:
    8. ... print(form.as_table())
    9. <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>
    10. <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>
    11. <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>
    12. <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>
    13. <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>
    14. <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>
    15. <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>
    16. <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>
    17. <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>

    Similar to can_order this adds a new field to each form named DELETE and is a forms.BooleanField. When data comes through marking any of the delete fields you can access them with deleted_forms:

    1. >>> data = {
    2. ... 'form-INITIAL_FORMS': '2',
    3. ... 'form-0-title': 'Article #1',
    4. ... 'form-0-pub_date': '2008-05-10',
    5. ... 'form-0-DELETE': 'on',
    6. ... 'form-1-title': 'Article #2',
    7. ... 'form-1-pub_date': '2008-05-11',
    8. ... 'form-1-DELETE': '',
    9. ... 'form-2-title': '',
    10. ... 'form-2-pub_date': '',
    11. ... 'form-2-DELETE': '',
    12. ... }
    13. >>> formset = ArticleFormSet(data, initial=[
    14. ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
    15. ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
    16. ... ])
    17. >>> [form.cleaned_data for form in formset.deleted_forms]
    18. [{'DELETE': True, 'pub_date': datetime.date(2008, 5, 10), 'title': 'Article #1'}]

    If you are using a , model instances for deleted forms will be deleted when you call formset.save().

    If you call formset.save(commit=False), objects will not be deleted automatically. You’ll need to call delete() on each of the formset.deleted_objects to actually delete them:

    On the other hand, if you are using a plain FormSet, it’s up to you to handle formset.deleted_forms, perhaps in your formset’s save() method, as there’s no general notion of what it means to delete a form.

    also provides a deletion_widget attribute and method that control the widget used with can_delete.

    deletion_widget

    New in Django 4.0.

    BaseFormSet.``deletion_widget

    Default: CheckboxInput

    Set deletion_widget to specify the widget class to be used with can_delete:

    1. >>> from django.forms import BaseFormSet, formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> class BaseArticleFormSet(BaseFormSet):
    4. ... deletion_widget = HiddenInput
    5. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_delete=True)

    get_deletion_widget

    New in Django 4.0.

    BaseFormSet.``get_deletion_widget()

    Override get_deletion_widget() if you need to provide a widget instance for use with can_delete:

    1. >>> from django.forms import BaseFormSet, formset_factory
    2. >>> from myapp.forms import ArticleForm
    3. >>> class BaseArticleFormSet(BaseFormSet):
    4. ... def get_deletion_widget(self):
    5. ... return HiddenInput(attrs={'class': 'deletion'})
    6. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_delete=True)

    can_delete_extra

    New in Django 3.2.

    BaseFormSet.``can_delete_extra

    Default: True

    While setting can_delete=True, specifying can_delete_extra=False will remove the option to delete extra forms.

    If you need to add additional fields to the formset this can be easily accomplished. The formset base class provides an add_fields method. You can override this method to add your own fields or even redefine the default fields/attributes of the order and deletion fields:

    1. >>> from django.forms import BaseFormSet
    2. >>> from django.forms import formset_factory
    3. >>> from myapp.forms import ArticleForm
    4. >>> class BaseArticleFormSet(BaseFormSet):
    5. ... def add_fields(self, form, index):
    6. ... super().add_fields(form, index)
    7. ... form.fields["my_field"] = forms.CharField()
    8. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
    9. >>> formset = ArticleFormSet()
    10. >>> for form in formset:
    11. ... print(form.as_table())
    12. <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>
    13. <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>
    14. <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>

    Passing custom parameters to formset forms

    Sometimes your form class takes custom parameters, like MyArticleForm. You can pass this parameter when instantiating the formset:

    1. >>> from django.forms import BaseFormSet
    2. >>> from django.forms import formset_factory
    3. >>> from myapp.forms import ArticleForm
    4. >>> class MyArticleForm(ArticleForm):
    5. ... def __init__(self, *args, user, **kwargs):
    6. ... self.user = user
    7. ... super().__init__(*args, **kwargs)
    8. >>> ArticleFormSet = formset_factory(MyArticleForm)
    9. >>> formset = ArticleFormSet(form_kwargs={'user': request.user})
    1. >>> from django.forms import BaseFormSet
    2. >>> from django.forms import formset_factory
    3. >>> class BaseArticleFormSet(BaseFormSet):
    4. ... def get_form_kwargs(self, index):
    5. ... kwargs = super().get_form_kwargs(index)
    6. ... kwargs['custom_kwarg'] = index
    7. ... return kwargs

    Customizing a formset’s prefix

    In the rendered HTML, formsets include a prefix on each field’s name. By default, the prefix is 'form', but it can be customized using the formset’s prefix argument.

    For example, in the default case, you might see:

    1. <label for="id_form-0-title">Title:</label>
    2. <input type="text" name="form-0-title" id="id_form-0-title">

    But with ArticleFormset(prefix='article') that becomes:

    1. <label for="id_article-0-title">Title:</label>
    2. <input type="text" name="article-0-title" id="id_article-0-title">

    This is useful if you want to .

    Formsets have five attributes and five methods associated with rendering.

    BaseFormSet.``renderer

    New in Django 4.0.

    Specifies the renderer to use for the formset. Defaults to the renderer specified by the setting.

    BaseFormSet.``template_name

    New in Django 4.0.

    The name of the template used when calling __str__ or render(). This template renders the formset’s management form and then each form in the formset as per the template defined by the form’s . This is a proxy of as_table by default.

    BaseFormSet.``template_name_p

    New in Django 4.0.

    The name of the template used when calling as_p(). By default this is 'django/forms/formsets/p.html'. This template renders the formset’s management form and then each form in the formset as per the form’s method.

    BaseFormSet.``template_name_table

    New in Django 4.0.

    The name of the template used when calling as_table(). By default this is 'django/forms/formsets/table.html'. This template renders the formset’s management form and then each form in the formset as per the form’s method.

    BaseFormSet.``template_name_ul

    New in Django 4.0.

    The name of the template used when calling as_ul(). By default this is 'django/forms/formsets/ul.html'. This template renders the formset’s management form and then each form in the formset as per the form’s method.

    BaseFormSet.``get_context()

    New in Django 4.0.

    Returns the context for rendering a formset in a template.

    The available context is:

    • formset : The instance of the formset.

    BaseFormSet.``render(template_name=None, context=None, renderer=None)

    New in Django 4.0.

    The render method is called by __str__ as well as the as_p(), , and as_table() methods. All arguments are optional and will default to:

    • template_name:
    • context: Value returned by get_context()
    • renderer: Value returned by

    BaseFormSet.``as_p()

    Renders the formset with the template_name_p template.

    BaseFormSet.``as_table()

    Renders the formset with the template.

    BaseFormSet.``as_ul()

    Renders the formset with the template_name_ul template.

    Using a formset inside a view is not very different from using a regular Form class. The only thing you will want to be aware of is making sure to use the management form inside the template. Let’s look at a sample view:

    1. from django.forms import formset_factory
    2. from django.shortcuts import render
    3. from myapp.forms import ArticleForm
    4. def manage_articles(request):
    5. ArticleFormSet = formset_factory(ArticleForm)
    6. if request.method == 'POST':
    7. formset = ArticleFormSet(request.POST, request.FILES)
    8. if formset.is_valid():
    9. # do something with the formset.cleaned_data
    10. pass
    11. else:
    12. formset = ArticleFormSet()
    13. return render(request, 'manage_articles.html', {'formset': formset})

    The manage_articles.html template might look like this:

    1. <form method="post">
    2. {{ formset.management_form }}
    3. <table>
    4. {% for form in formset %}
    5. {{ form }}
    6. {% endfor %}
    7. </table>
    8. </form>

    However there’s a slight shortcut for the above by letting the formset itself deal with the management form:

    1. <form method="post">
    2. <table>
    3. {{ formset }}
    4. </table>
    5. </form>

    The above ends up calling the method on the formset class. This renders the formset using the template specified by the template_name attribute. Similar to forms, by default the formset will be rendered as_table, with other helper methods of as_p and as_ul being available. The rendering of the formset can be customized by specifying the template_name attribute, or more generally by .

    Changed in Django 4.0:

    Rendering of formsets was moved to the template engine.

    Manually rendered can_delete and can_order

    If you manually render fields in the template, you can render can_delete parameter with {{ form.DELETE }}:

    1. <form method="post">
    2. {{ formset.management_form }}
    3. {% for form in formset %}
    4. <ul>
    5. <li>{{ form.title }}</li>
    6. <li>{{ form.pub_date }}</li>
    7. {% if formset.can_delete %}
    8. <li>{{ form.DELETE }}</li>
    9. {% endif %}
    10. </ul>
    11. {% endfor %}

    Similarly, if the formset has the ability to order (can_order=True), it is possible to render it with {{ form.ORDER }}.

    Using more than one formset in a view

    You are able to use more than one formset in a view if you like. Formsets borrow much of its behavior from forms. With that said you are able to use prefix to prefix formset form field names with a given value to allow more than one formset to be sent to a view without name clashing. Let’s take a look at how this might be accomplished:

    Each formset’s prefix replaces the default form prefix that’s added to each field’s and id HTML attributes.