2016-01-03 10:56:22 +00:00
========
2008-08-23 22:25:40 +00:00
Formsets
========
2019-06-03 10:39:48 +00:00
.. currentmodule:: django.forms.formsets
2013-07-12 13:52:18 +00:00
.. class:: BaseFormSet
2013-01-01 13:12:42 +00:00
2013-04-15 16:19:17 +00:00
A formset is a layer of abstraction to work with multiple forms on the same
2008-08-23 22:25:40 +00:00
page. It can be best compared to a data grid. Let's say you have the following
form:
2023-02-09 15:48:46 +00:00
2008-08-23 22:25:40 +00:00
.. code-block:: pycon
>>> from django import forms
>>> class ArticleForm(forms.Form):
... title = forms.CharField()
... pub_date = forms.DateField()
You might want to allow the user to create several articles at once. To create
a formset out of an ``ArticleForm`` you would do:
2023-02-09 15:48:46 +00:00
2008-08-23 22:25:40 +00:00
.. code-block:: pycon
2015-10-28 01:37:35 +00:00
>>> from django.forms import formset_factory
2008-08-23 22:25:40 +00:00
>>> ArticleFormSet = formset_factory(ArticleForm)
2019-10-30 07:39:23 +00:00
You now have created a formset class named ``ArticleFormSet``.
2020-11-05 09:40:41 +00:00
Instantiating the formset gives you the ability to iterate over the forms
2019-10-30 07:39:23 +00:00
in the formset and display them as you would with a regular form:
2023-02-09 15:48:46 +00:00
2019-10-30 07:39:23 +00:00
.. code-block:: pycon
2008-08-23 22:25:40 +00:00
>>> formset = ArticleFormSet()
2010-12-19 13:41:43 +00:00
>>> for form in formset:
2012-04-28 16:02:01 +00:00
... print(form.as_table())
2018-01-21 07:09:10 +00:00
<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>
<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>
2008-08-23 22:25:40 +00:00
2010-05-10 14:03:11 +00:00
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,
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
:func:`~django.forms.formsets.formset_factory` defines one extra form; the
2019-10-30 07:39:23 +00:00
following example will create a formset class to display two blank forms:
2023-02-09 15:48:46 +00:00
2019-10-30 07:39:23 +00:00
.. code-block:: pycon
2008-08-23 22:25:40 +00:00
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
2019-10-30 07:39:23 +00:00
Iterating over a formset will render the forms in the order they were
2012-09-19 20:39:14 +00:00
created. You can change this order by providing an alternate implementation for
2012-12-29 15:35:12 +00:00
the ``__iter__()`` method.
2010-12-19 13:41:43 +00:00
2011-09-10 01:53:56 +00:00
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.
2012-01-15 01:36:14 +00:00
.. _formsets-initial-data:
2008-08-23 22:25:40 +00:00
Using initial data with a formset
2016-01-03 10:56:22 +00:00
=================================
2008-08-23 22:25:40 +00:00
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
2014-06-08 18:30:52 +00:00
number of forms it generates from the initial data. Let's take a look at an
2008-08-23 22:25:40 +00:00
example:
2023-02-09 15:48:46 +00:00
2008-08-23 22:25:40 +00:00
.. code-block:: pycon
2013-05-19 09:15:35 +00:00
>>> import datetime
2015-10-28 01:37:35 +00:00
>>> from django.forms import formset_factory
2013-05-20 17:56:19 +00:00
>>> from myapp.forms import ArticleForm
2008-08-23 22:25:40 +00:00
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
2011-08-18 21:47:04 +00:00
>>> formset = ArticleFormSet(initial=[
2014-03-22 20:30:49 +00:00
... {'title': 'Django is now open source',
2011-08-18 21:47:04 +00:00
... 'pub_date': datetime.date.today(),}
... ])
2008-08-23 22:25:40 +00:00
2010-12-19 13:41:43 +00:00
>>> for form in formset:
2012-04-28 16:02:01 +00:00
... print(form.as_table())
2018-01-21 07:09:10 +00:00
<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>
<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>
<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>
<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>
<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>
<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>
2008-08-23 22:25:40 +00:00
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.
2016-10-10 19:36:21 +00:00
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=[...])``.
2009-05-14 02:13:08 +00:00
.. seealso::
:ref:`Creating formsets from models with model formsets <model-formsets>`.
2010-05-12 11:56:42 +00:00
.. _formsets-max-num:
2008-08-23 22:25:40 +00:00
Limiting the maximum number of forms
2016-01-03 10:56:22 +00:00
====================================
2008-08-23 22:25:40 +00:00
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
The ``max_num`` parameter to :func:`~django.forms.formsets.formset_factory`
2014-09-06 20:58:26 +00:00
gives you the ability to limit the number of forms the formset will display:
2023-02-09 15:48:46 +00:00
2014-09-06 20:58:26 +00:00
.. code-block:: pycon
2008-08-23 22:25:40 +00:00
2015-10-28 01:37:35 +00:00
>>> from django.forms import formset_factory
2013-05-20 17:56:19 +00:00
>>> from myapp.forms import ArticleForm
2008-08-23 22:25:40 +00:00
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
2013-02-12 14:14:19 +00:00
>>> formset = ArticleFormSet()
2010-12-19 13:41:43 +00:00
>>> for form in formset:
2012-04-28 16:02:01 +00:00
... print(form.as_table())
2018-01-21 07:09:10 +00:00
<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>
<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>
2008-08-23 22:25:40 +00:00
2014-09-06 20:58:26 +00:00
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
2014-09-10 15:17:33 +00:00
example, if ``extra=2`` and ``max_num=2`` and the formset is initialized with
2014-09-06 20:58:26 +00:00
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.
2010-03-27 23:03:56 +00:00
2013-02-12 10:22:41 +00:00
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.
2010-03-27 23:03:56 +00:00
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
By default, ``max_num`` only affects how many forms are displayed and does not
affect validation. If ``validate_max=True`` is passed to the
:func:`~django.forms.formsets.formset_factory`, then ``max_num`` will affect
validation. See :ref:`validate_max`.
2020-04-30 07:34:53 +00:00
.. _formsets-absolute-max:
Limiting the maximum number of instantiated forms
=================================================
The ``absolute_max`` parameter to :func:`.formset_factory` allows limiting the
number of forms that can be instantiated when supplying ``POST`` data. This
protects against memory exhaustion attacks using forged ``POST`` requests:
2023-02-09 15:48:46 +00:00
2020-04-30 07:34:53 +00:00
.. code-block:: pycon
>>> from django.forms.formsets import formset_factory
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm, absolute_max=1500)
>>> data = {
... 'form-TOTAL_FORMS': '1501',
... 'form-INITIAL_FORMS': '0',
... }
>>> formset = ArticleFormSet(data)
>>> len(formset.forms)
1500
>>> formset.is_valid()
False
>>> formset.non_form_errors()
2020-09-23 20:08:15 +00:00
['Please submit at most 1000 forms.']
2020-04-30 07:34:53 +00:00
2020-12-15 06:19:00 +00:00
When ``absolute_max`` is ``None``, it defaults to ``max_num + 1000``. (If
2020-04-30 07:34:53 +00:00
``max_num`` is ``None``, it defaults to ``2000``).
If ``absolute_max`` is less than ``max_num``, a ``ValueError`` will be raised.
2008-08-23 22:25:40 +00:00
Formset validation
2016-01-03 10:56:22 +00:00
==================
2008-08-23 22:25:40 +00:00
2009-07-15 13:52:39 +00:00
Validation with a formset is almost identical to a regular ``Form``. There is
2008-08-23 22:25:40 +00:00
an ``is_valid`` method on the formset to provide a convenient way to validate
2009-07-15 13:52:39 +00:00
all forms in the formset:
2023-02-09 15:48:46 +00:00
2009-07-15 13:52:39 +00:00
.. code-block:: pycon
2008-08-23 22:25:40 +00:00
2015-10-28 01:37:35 +00:00
>>> from django.forms import formset_factory
2013-05-20 17:56:19 +00:00
>>> from myapp.forms import ArticleForm
2008-08-23 22:25:40 +00:00
>>> ArticleFormSet = formset_factory(ArticleForm)
2010-11-21 17:27:01 +00:00
>>> data = {
2014-03-22 20:30:49 +00:00
... 'form-TOTAL_FORMS': '1',
... 'form-INITIAL_FORMS': '0',
2010-11-21 17:27:01 +00:00
... }
>>> formset = ArticleFormSet(data)
2008-08-23 22:25:40 +00:00
>>> formset.is_valid()
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
2009-07-15 13:52:39 +00:00
provide an invalid article:
2023-02-09 15:48:46 +00:00
2009-07-15 13:52:39 +00:00
.. code-block:: pycon
2008-08-23 22:25:40 +00:00
>>> data = {
2014-03-22 20:30:49 +00:00
... 'form-TOTAL_FORMS': '2',
... 'form-INITIAL_FORMS': '0',
... 'form-0-title': 'Test',
... 'form-0-pub_date': '1904-06-16',
... 'form-1-title': 'Test',
... 'form-1-pub_date': '', # <-- this date is missing but required
2008-08-23 22:25:40 +00:00
... }
>>> formset = ArticleFormSet(data)
>>> formset.is_valid()
False
>>> formset.errors
2014-03-22 20:30:49 +00:00
[{}, {'pub_date': ['This field is required.']}]
2008-08-23 22:25:40 +00:00
2009-07-15 13:52:39 +00:00
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.
2008-08-23 22:25:40 +00:00
2016-09-26 13:31:01 +00:00
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.
2016-03-28 18:02:04 +00:00
2014-01-22 21:17:32 +00:00
.. method:: BaseFormSet.total_error_count()
2013-06-15 20:34:25 +00:00
To check how many errors there are in the formset, we can use the
``total_error_count`` method:
2023-02-09 15:48:46 +00:00
2013-06-15 20:34:25 +00:00
.. code-block:: pycon
>>> # Using the previous example
>>> formset.errors
2014-03-22 20:30:49 +00:00
[{}, {'pub_date': ['This field is required.']}]
2013-06-15 20:34:25 +00:00
>>> len(formset.errors)
2
>>> formset.total_error_count()
1
2011-09-10 02:42:05 +00:00
We can also check if form data differs from the initial data (i.e. the form was
sent without any data):
2023-02-09 15:48:46 +00:00
2011-09-10 02:42:05 +00:00
.. code-block:: pycon
>>> data = {
2014-03-22 20:30:49 +00:00
... 'form-TOTAL_FORMS': '1',
... 'form-INITIAL_FORMS': '0',
... 'form-0-title': '',
... 'form-0-pub_date': '',
2011-09-10 02:42:05 +00:00
... }
>>> formset = ArticleFormSet(data)
>>> formset.has_changed()
False
2008-12-23 00:01:09 +00:00
.. _understanding-the-managementform:
2016-01-24 21:26:11 +00:00
Understanding the ``ManagementForm``
------------------------------------
2008-08-23 22:25:40 +00:00
2010-05-10 14:07:05 +00:00
You may have noticed the additional data (``form-TOTAL_FORMS``,
2020-10-25 19:50:02 +00:00
``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:
2023-02-09 15:48:46 +00:00
2020-10-25 19:50:02 +00:00
.. code-block:: pycon
2008-08-23 22:25:40 +00:00
>>> data = {
2014-03-22 20:30:49 +00:00
... 'form-0-title': 'Test',
... 'form-0-pub_date': '',
2008-08-23 22:25:40 +00:00
... }
>>> formset = ArticleFormSet(data)
2015-05-22 14:53:55 +00:00
>>> formset.is_valid()
2020-11-05 09:40:41 +00:00
False
2008-08-23 22:25:40 +00:00
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
2013-03-31 08:34:28 +00:00
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.
2008-08-23 22:25:40 +00:00
2010-05-10 14:07:05 +00:00
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).
2020-10-25 19:50:02 +00:00
.. 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.
2009-03-30 15:58:52 +00:00
``total_form_count`` and ``initial_form_count``
2016-01-03 10:56:22 +00:00
-----------------------------------------------
2009-03-30 15:58:52 +00:00
2010-01-10 17:45:55 +00:00
``BaseFormSet`` has a couple of methods that are closely related to the
2009-03-30 15:58:52 +00:00
``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.
2015-06-04 10:47:43 +00:00
.. _empty_form:
2010-01-26 15:02:53 +00:00
``empty_form``
2016-01-03 10:56:22 +00:00
--------------
2010-01-26 15:02:53 +00:00
``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.
2022-05-07 22:53:13 +00:00
.. _formsets-error-messages:
2020-11-05 09:40:41 +00:00
``error_messages``
------------------
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
2022-05-07 22:53:13 +00:00
you want to override. Error message keys include ``'too_few_forms'``,
``'too_many_forms'``, and ``'missing_management_form'``. The
``'too_few_forms'`` and ``'too_many_forms'`` error messages may contain
``%(num)d``, which will be replaced with ``min_num`` and ``max_num``,
respectively.
For example, here is the default error message when the
2020-11-05 09:40:41 +00:00
management form is missing:
2023-02-09 15:48:46 +00:00
2020-11-05 09:40:41 +00:00
.. code-block:: pycon
>>> formset = ArticleFormSet({})
>>> formset.is_valid()
False
>>> formset.non_form_errors()
['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.']
And here is a custom error message:
2023-02-09 15:48:46 +00:00
2020-11-05 09:40:41 +00:00
.. code-block:: pycon
>>> formset = ArticleFormSet({}, error_messages={'missing_management_form': 'Sorry, something went wrong.'})
>>> formset.is_valid()
False
>>> formset.non_form_errors()
['Sorry, something went wrong.']
2022-05-07 22:53:13 +00:00
.. versionchanged:: 4.1
The ``'too_few_forms'`` and ``'too_many_forms'`` keys were added.
2008-08-23 22:25:40 +00:00
Custom formset validation
2016-01-03 10:56:22 +00:00
-------------------------
2008-08-23 22:25:40 +00:00
A formset has a ``clean`` method similar to the one on a ``Form`` class. This
2009-07-15 13:52:39 +00:00
is where you define your own validation that works at the formset level:
2023-02-09 15:48:46 +00:00
2009-07-15 13:52:39 +00:00
.. code-block:: pycon
2008-08-23 22:25:40 +00:00
2020-02-12 13:48:49 +00:00
>>> from django.core.exceptions import ValidationError
2015-10-28 01:37:35 +00:00
>>> from django.forms import BaseFormSet
>>> from django.forms import formset_factory
2013-05-19 09:15:35 +00:00
>>> from myapp.forms import ArticleForm
2008-08-23 22:25:40 +00:00
>>> class BaseArticleFormSet(BaseFormSet):
... def clean(self):
2009-07-15 13:52:39 +00:00
... """Checks that no two articles have the same title."""
... if any(self.errors):
... # Don't bother validating the formset unless each form is valid on its own
... return
... titles = []
2013-06-11 15:05:19 +00:00
... for form in self.forms:
2019-04-16 07:24:48 +00:00
... if self.can_delete and self._should_delete_form(form):
... continue
... title = form.cleaned_data.get('title')
2009-07-15 13:52:39 +00:00
... if title in titles:
2020-02-12 13:48:49 +00:00
... raise ValidationError("Articles in a set must have distinct titles.")
2009-07-15 13:52:39 +00:00
... titles.append(title)
2008-08-23 22:25:40 +00:00
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
2009-07-15 13:52:39 +00:00
>>> data = {
2014-03-22 20:30:49 +00:00
... 'form-TOTAL_FORMS': '2',
... 'form-INITIAL_FORMS': '0',
... 'form-0-title': 'Test',
... 'form-0-pub_date': '1904-06-16',
... 'form-1-title': 'Test',
... 'form-1-pub_date': '1912-06-23',
2009-07-15 13:52:39 +00:00
... }
>>> formset = ArticleFormSet(data)
2008-08-23 22:25:40 +00:00
>>> formset.is_valid()
False
2009-07-15 13:52:39 +00:00
>>> formset.errors
[{}, {}]
2008-08-23 22:25:40 +00:00
>>> formset.non_form_errors()
2014-03-22 20:30:49 +00:00
['Articles in a set must have distinct titles.']
2008-08-23 22:25:40 +00:00
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.
2021-07-07 20:50:30 +00:00
Non-form errors will be rendered with an additional class of ``nonform`` to
help distinguish them from form-specific errors. For example,
``{{ formset.non_form_errors }}`` would look like:
.. code-block:: html+django
<ul class="errorlist nonform">
<li>Articles in a set must have distinct titles.</li>
</ul>
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
Validating the number of forms in a formset
2016-01-03 10:56:22 +00:00
===========================================
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
2013-05-24 06:02:07 +00:00
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.
2016-09-26 17:54:26 +00:00
.. _validate_max:
2013-05-24 06:02:07 +00:00
``validate_max``
2016-01-03 10:56:22 +00:00
----------------
2013-05-24 06:02:07 +00:00
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
If ``validate_max=True`` is passed to
:func:`~django.forms.formsets.formset_factory`, validation will also check
2013-05-20 16:13:03 +00:00
that the number of forms in the data set, minus those marked for
deletion, is less than or equal to ``max_num``.
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
2015-10-28 01:37:35 +00:00
>>> from django.forms import formset_factory
2013-05-19 09:15:35 +00:00
>>> from myapp.forms import ArticleForm
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
>>> ArticleFormSet = formset_factory(ArticleForm, max_num=1, validate_max=True)
>>> data = {
2014-03-22 20:30:49 +00:00
... 'form-TOTAL_FORMS': '2',
... 'form-INITIAL_FORMS': '0',
... 'form-0-title': 'Test',
... 'form-0-pub_date': '1904-06-16',
... 'form-1-title': 'Test 2',
... 'form-1-pub_date': '1912-06-23',
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
... }
>>> formset = ArticleFormSet(data)
>>> formset.is_valid()
False
>>> formset.errors
[{}, {}]
>>> formset.non_form_errors()
2020-09-23 20:08:15 +00:00
['Please submit at most 1 form.']
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
``validate_max=True`` validates against ``max_num`` strictly even if
``max_num`` was exceeded because the amount of initial data supplied was
excessive.
2022-05-07 22:53:13 +00:00
The error message can be customized by passing the ``'too_many_forms'`` message
to the :ref:`formsets-error-messages` argument.
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
.. note::
Regardless of ``validate_max``, if the number of forms in a data set
2020-04-30 07:34:53 +00:00
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 :ref:`formsets-absolute-max`.
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
2013-05-24 06:02:07 +00:00
``validate_min``
2016-01-03 10:56:22 +00:00
----------------
2013-05-24 06:02:07 +00:00
If ``validate_min=True`` is passed to
:func:`~django.forms.formsets.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``.
2015-10-28 01:37:35 +00:00
>>> from django.forms import formset_factory
2013-05-24 06:02:07 +00:00
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm, min_num=3, validate_min=True)
>>> data = {
2014-03-22 20:30:49 +00:00
... 'form-TOTAL_FORMS': '2',
... 'form-INITIAL_FORMS': '0',
... 'form-0-title': 'Test',
... 'form-0-pub_date': '1904-06-16',
... 'form-1-title': 'Test 2',
... 'form-1-pub_date': '1912-06-23',
2013-05-24 06:02:07 +00:00
... }
>>> formset = ArticleFormSet(data)
>>> formset.is_valid()
False
>>> formset.errors
[{}, {}]
>>> formset.non_form_errors()
2020-09-23 20:08:15 +00:00
['Please submit at least 3 forms.']
2013-05-24 06:02:07 +00:00
2022-05-07 22:53:13 +00:00
The error message can be customized by passing the ``'too_few_forms'`` message
to the :ref:`formsets-error-messages` argument.
2020-08-18 20:56:39 +00:00
.. note::
Regardless of ``validate_min``, if a formset contains no data, then
``extra + min_num`` empty forms will be displayed.
2008-08-23 22:25:40 +00:00
Dealing with ordering and deletion of forms
2016-01-03 10:56:22 +00:00
===========================================
2008-08-23 22:25:40 +00:00
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
The :func:`~django.forms.formsets.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.
2008-08-23 22:25:40 +00:00
``can_order``
2016-01-03 10:56:22 +00:00
-------------
2008-08-23 22:25:40 +00:00
2013-07-12 13:52:18 +00:00
.. attribute:: BaseFormSet.can_order
2008-08-23 22:25:40 +00:00
Default: ``False``
2011-10-04 23:54:12 +00:00
Lets you create a formset with the ability to order:
2023-02-09 15:48:46 +00:00
2011-10-04 23:54:12 +00:00
.. code-block:: pycon
2008-08-23 22:25:40 +00:00
2015-10-28 01:37:35 +00:00
>>> from django.forms import formset_factory
2013-05-19 09:15:35 +00:00
>>> from myapp.forms import ArticleForm
2008-08-23 22:25:40 +00:00
>>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)
>>> formset = ArticleFormSet(initial=[
2014-03-22 20:30:49 +00:00
... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
2008-08-23 22:25:40 +00:00
... ])
2010-12-19 13:41:43 +00:00
>>> for form in formset:
2012-04-28 16:02:01 +00:00
... print(form.as_table())
2018-01-21 07:09:10 +00:00
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
2008-08-23 22:25:40 +00:00
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
2011-10-04 23:54:12 +00:00
data it automatically assigned them a numeric value. Let's look at what will
2008-08-23 22:25:40 +00:00
happen when the user changes these values:
2023-02-09 15:48:46 +00:00
2008-08-23 22:25:40 +00:00
.. code-block:: pycon
>>> data = {
2014-03-22 20:30:49 +00:00
... 'form-TOTAL_FORMS': '3',
... 'form-INITIAL_FORMS': '2',
... 'form-0-title': 'Article #1',
... 'form-0-pub_date': '2008-05-10',
... 'form-0-ORDER': '2',
... 'form-1-title': 'Article #2',
... 'form-1-pub_date': '2008-05-11',
... 'form-1-ORDER': '1',
... 'form-2-title': 'Article #3',
... 'form-2-pub_date': '2008-05-01',
... 'form-2-ORDER': '0',
2008-08-23 22:25:40 +00:00
... }
>>> formset = ArticleFormSet(data, initial=[
2014-03-22 20:30:49 +00:00
... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
2008-08-23 22:25:40 +00:00
... ])
>>> formset.is_valid()
True
>>> for form in formset.ordered_forms:
2012-04-28 16:02:01 +00:00
... print(form.cleaned_data)
2014-03-22 20:30:49 +00:00
{'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': 'Article #3'}
{'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': 'Article #2'}
{'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': 'Article #1'}
2008-08-23 22:25:40 +00:00
2018-11-21 20:58:04 +00:00
:class:`~django.forms.formsets.BaseFormSet` also provides an
:attr:`~django.forms.formsets.BaseFormSet.ordering_widget` attribute and
:meth:`~django.forms.formsets.BaseFormSet.get_ordering_widget` method that
control the widget used with
:attr:`~django.forms.formsets.BaseFormSet.can_order`.
``ordering_widget``
^^^^^^^^^^^^^^^^^^^
.. attribute:: BaseFormSet.ordering_widget
Default: :class:`~django.forms.NumberInput`
Set ``ordering_widget`` to specify the widget class to be used with
``can_order``:
2023-02-09 15:48:46 +00:00
2018-11-21 20:58:04 +00:00
.. code-block:: pycon
>>> from django.forms import BaseFormSet, formset_factory
>>> from myapp.forms import ArticleForm
>>> class BaseArticleFormSet(BaseFormSet):
... ordering_widget = HiddenInput
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)
``get_ordering_widget``
^^^^^^^^^^^^^^^^^^^^^^^
.. method:: BaseFormSet.get_ordering_widget()
Override ``get_ordering_widget()`` if you need to provide a widget instance for
use with ``can_order``:
2023-02-09 15:48:46 +00:00
2018-11-21 20:58:04 +00:00
.. code-block:: pycon
>>> from django.forms import BaseFormSet, formset_factory
>>> from myapp.forms import ArticleForm
>>> class BaseArticleFormSet(BaseFormSet):
... def get_ordering_widget(self):
... return HiddenInput(attrs={'class': 'ordering'})
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)
2008-08-23 22:25:40 +00:00
``can_delete``
2016-01-03 10:56:22 +00:00
--------------
2008-08-23 22:25:40 +00:00
2013-07-12 13:52:18 +00:00
.. attribute:: BaseFormSet.can_delete
2008-08-23 22:25:40 +00:00
Default: ``False``
2013-07-08 16:08:30 +00:00
Lets you create a formset with the ability to select forms for deletion:
2023-02-09 15:48:46 +00:00
2013-07-08 16:08:30 +00:00
.. code-block:: pycon
2008-08-23 22:25:40 +00:00
2015-10-28 01:37:35 +00:00
>>> from django.forms import formset_factory
2013-05-19 09:15:35 +00:00
>>> from myapp.forms import ArticleForm
2008-08-23 22:25:40 +00:00
>>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True)
>>> formset = ArticleFormSet(initial=[
2014-03-22 20:30:49 +00:00
... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
2008-08-23 22:25:40 +00:00
... ])
2010-12-19 13:41:43 +00:00
>>> for form in formset:
2015-05-22 14:53:55 +00:00
... print(form.as_table())
2018-01-21 07:09:10 +00:00
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
2008-08-23 22:25:40 +00:00
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``:
2023-02-09 15:48:46 +00:00
2008-08-23 22:25:40 +00:00
.. code-block:: pycon
>>> data = {
2014-03-22 20:30:49 +00:00
... 'form-TOTAL_FORMS': '3',
... 'form-INITIAL_FORMS': '2',
... 'form-0-title': 'Article #1',
... 'form-0-pub_date': '2008-05-10',
... 'form-0-DELETE': 'on',
... 'form-1-title': 'Article #2',
... 'form-1-pub_date': '2008-05-11',
... 'form-1-DELETE': '',
... 'form-2-title': '',
... 'form-2-pub_date': '',
... 'form-2-DELETE': '',
2008-08-23 22:25:40 +00:00
... }
>>> formset = ArticleFormSet(data, initial=[
2014-03-22 20:30:49 +00:00
... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
2008-08-23 22:25:40 +00:00
... ])
>>> [form.cleaned_data for form in formset.deleted_forms]
2014-03-22 20:30:49 +00:00
[{'DELETE': True, 'pub_date': datetime.date(2008, 5, 10), 'title': 'Article #1'}]
2008-08-23 22:25:40 +00:00
2013-07-08 16:08:30 +00:00
If you are using a :class:`ModelFormSet<django.forms.models.BaseModelFormSet>`,
model instances for deleted forms will be deleted when you call
2013-07-12 13:52:18 +00:00
``formset.save()``.
2015-01-26 20:39:52 +00:00
If you call ``formset.save(commit=False)``, objects will not be deleted
automatically. You'll need to call ``delete()`` on each of the
:attr:`formset.deleted_objects
<django.forms.models.BaseModelFormSet.deleted_objects>` to actually delete
them:
2023-02-09 15:48:46 +00:00
2015-01-26 20:39:52 +00:00
.. code-block:: pycon
>>> instances = formset.save(commit=False)
>>> for obj in formset.deleted_objects:
... obj.delete()
2014-06-04 16:37:10 +00:00
2013-07-12 13:52:18 +00:00
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.
2013-07-08 16:08:30 +00:00
2021-08-03 10:27:22 +00:00
:class:`~django.forms.formsets.BaseFormSet` also provides a
:attr:`~django.forms.formsets.BaseFormSet.deletion_widget` attribute and
:meth:`~django.forms.formsets.BaseFormSet.get_deletion_widget` method that
control the widget used with
:attr:`~django.forms.formsets.BaseFormSet.can_delete`.
``deletion_widget``
^^^^^^^^^^^^^^^^^^^
.. attribute:: BaseFormSet.deletion_widget
Default: :class:`~django.forms.CheckboxInput`
Set ``deletion_widget`` to specify the widget class to be used with
``can_delete``:
2023-02-09 15:48:46 +00:00
2021-08-03 10:27:22 +00:00
.. code-block:: pycon
>>> from django.forms import BaseFormSet, formset_factory
>>> from myapp.forms import ArticleForm
>>> class BaseArticleFormSet(BaseFormSet):
... deletion_widget = HiddenInput
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_delete=True)
``get_deletion_widget``
^^^^^^^^^^^^^^^^^^^^^^^
.. method:: BaseFormSet.get_deletion_widget()
Override ``get_deletion_widget()`` if you need to provide a widget instance for
use with ``can_delete``:
2023-02-09 15:48:46 +00:00
2021-08-03 10:27:22 +00:00
.. code-block:: pycon
>>> from django.forms import BaseFormSet, formset_factory
>>> from myapp.forms import ArticleForm
>>> class BaseArticleFormSet(BaseFormSet):
... def get_deletion_widget(self):
... return HiddenInput(attrs={'class': 'deletion'})
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_delete=True)
2020-06-19 21:46:25 +00:00
``can_delete_extra``
--------------------
.. attribute:: BaseFormSet.can_delete_extra
Default: ``True``
While setting ``can_delete=True``, specifying ``can_delete_extra=False`` will
remove the option to delete extra forms.
2008-08-23 22:25:40 +00:00
Adding additional fields to a formset
2016-01-03 10:56:22 +00:00
=====================================
2008-08-23 22:25:40 +00:00
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
2019-06-17 14:54:55 +00:00
can override this method to add your own fields or even redefine the default
fields/attributes of the order and deletion fields:
2023-02-09 15:48:46 +00:00
2019-06-17 14:54:55 +00:00
.. code-block:: pycon
2008-08-23 22:25:40 +00:00
2015-10-28 01:37:35 +00:00
>>> from django.forms import BaseFormSet
>>> from django.forms import formset_factory
2013-05-19 09:15:35 +00:00
>>> from myapp.forms import ArticleForm
2008-08-23 22:25:40 +00:00
>>> class BaseArticleFormSet(BaseFormSet):
... def add_fields(self, form, index):
2017-01-22 06:57:14 +00:00
... super().add_fields(form, index)
2008-08-23 22:25:40 +00:00
... form.fields["my_field"] = forms.CharField()
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
>>> formset = ArticleFormSet()
2010-12-19 13:41:43 +00:00
>>> for form in formset:
2012-04-28 16:02:01 +00:00
... print(form.as_table())
2018-01-21 07:09:10 +00:00
<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>
<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>
<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>
2008-08-23 22:25:40 +00:00
2015-06-05 10:42:58 +00:00
.. _custom-formset-form-kwargs:
2015-06-04 10:47:43 +00:00
Passing custom parameters to formset forms
2016-01-03 10:56:22 +00:00
==========================================
2015-06-04 10:47:43 +00:00
Sometimes your form class takes custom parameters, like ``MyArticleForm``.
You can pass this parameter when instantiating the formset:
2023-02-09 15:48:46 +00:00
2015-06-04 10:47:43 +00:00
.. code-block:: pycon
2015-10-28 01:37:35 +00:00
>>> from django.forms import BaseFormSet
>>> from django.forms import formset_factory
2015-06-04 10:47:43 +00:00
>>> from myapp.forms import ArticleForm
>>> class MyArticleForm(ArticleForm):
2017-02-01 16:41:56 +00:00
... def __init__(self, *args, user, **kwargs):
... self.user = user
2017-01-22 06:57:14 +00:00
... super().__init__(*args, **kwargs)
2015-06-04 10:47:43 +00:00
>>> ArticleFormSet = formset_factory(MyArticleForm)
>>> formset = ArticleFormSet(form_kwargs={'user': request.user})
The ``form_kwargs`` may also depend on the specific form instance. The formset
base class provides a ``get_form_kwargs`` method. The method takes a single
argument - the index of the form in the formset. The index is ``None`` for the
:ref:`empty_form`:
2023-02-09 15:48:46 +00:00
2015-06-04 10:47:43 +00:00
.. code-block:: pycon
2015-10-28 01:37:35 +00:00
>>> from django.forms import BaseFormSet
>>> from django.forms import formset_factory
2015-06-04 10:47:43 +00:00
>>> class BaseArticleFormSet(BaseFormSet):
... def get_form_kwargs(self, index):
2017-01-22 06:57:14 +00:00
... kwargs = super().get_form_kwargs(index)
2015-06-04 10:47:43 +00:00
... kwargs['custom_kwarg'] = index
... return kwargs
2022-11-24 14:16:31 +00:00
>>> ArticleFormSet = formset_factory(MyArticleForm, formset=BaseArticleFormSet)
>>> formset = ArticleFormSet()
2017-11-01 19:40:49 +00:00
.. _formset-prefix:
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:
.. code-block:: html
<label for="id_form-0-title">Title:</label>
2018-01-21 07:09:10 +00:00
<input type="text" name="form-0-title" id="id_form-0-title">
2017-11-01 19:40:49 +00:00
But with ``ArticleFormset(prefix='article')`` that becomes:
.. code-block:: html
<label for="id_article-0-title">Title:</label>
2018-01-21 07:09:10 +00:00
<input type="text" name="article-0-title" id="id_article-0-title">
2017-11-01 19:40:49 +00:00
This is useful if you want to :ref:`use more than one formset in a view
<multiple-formsets-in-view>`.
2021-09-10 07:06:01 +00:00
.. _formset-rendering:
2008-08-23 22:25:40 +00:00
Using a formset in views and templates
2016-01-03 10:56:22 +00:00
======================================
2008-08-23 22:25:40 +00:00
2021-12-28 11:36:57 +00:00
Formsets have the following attributes and methods associated with rendering:
2021-09-10 07:06:01 +00:00
.. attribute:: BaseFormSet.renderer
Specifies the :doc:`renderer </ref/forms/renderers>` to use for the
formset. Defaults to the renderer specified by the :setting:`FORM_RENDERER`
setting.
.. attribute:: BaseFormSet.template_name
2022-04-26 14:01:59 +00:00
The name of the template rendered if the formset is cast into a string,
e.g. via ``print(formset)`` or in a template via ``{{ formset }}``.
By default, a property returning the value of the renderer's
:attr:`~django.forms.renderers.BaseRenderer.formset_template_name`. You may
set it as a string template name in order to override that for a particular
formset class.
This template will be used to render the formset's management form, and
then each form in the formset as per the template defined by the form's
:attr:`~django.forms.Form.template_name`.
.. versionchanged:: 4.1
In older versions ``template_name`` defaulted to the string value
``'django/forms/formset/default.html'``.
2021-09-10 07:06:01 +00:00
2022-05-05 07:21:47 +00:00
.. attribute:: BaseFormSet.template_name_div
.. versionadded:: 4.1
The name of the template used when calling :meth:`.as_div`. By default this
is ``"django/forms/formsets/div.html"``. This template renders the
formset's management form and then each form in the formset as per the
form's :meth:`~django.forms.Form.as_div` method.
2021-09-10 07:06:01 +00:00
.. attribute:: BaseFormSet.template_name_p
The name of the template used when calling :meth:`.as_p`. By default this
2022-05-05 07:21:47 +00:00
is ``"django/forms/formsets/p.html"``. This template renders the formset's
2021-09-22 03:12:26 +00:00
management form and then each form in the formset as per the form's
2021-09-10 07:06:01 +00:00
:meth:`~django.forms.Form.as_p` method.
.. attribute:: BaseFormSet.template_name_table
The name of the template used when calling :meth:`.as_table`. By default
2022-05-05 07:21:47 +00:00
this is ``"django/forms/formsets/table.html"``. This template renders the
2021-09-22 03:12:26 +00:00
formset's management form and then each form in the formset as per the
form's :meth:`~django.forms.Form.as_table` method.
2021-09-10 07:06:01 +00:00
.. attribute:: BaseFormSet.template_name_ul
The name of the template used when calling :meth:`.as_ul`. By default this
2022-05-05 07:21:47 +00:00
is ``"django/forms/formsets/ul.html"``. This template renders the formset's
2021-09-22 03:12:26 +00:00
management form and then each form in the formset as per the form's
2021-09-10 07:06:01 +00:00
:meth:`~django.forms.Form.as_ul` method.
.. method:: BaseFormSet.get_context()
Returns the context for rendering a formset in a template.
The available context is:
* ``formset`` : The instance of the formset.
.. method:: BaseFormSet.render(template_name=None, context=None, renderer=None)
The render method is called by ``__str__`` as well as the :meth:`.as_p`,
:meth:`.as_ul`, and :meth:`.as_table` methods. All arguments are optional
and will default to:
* ``template_name``: :attr:`.template_name`
* ``context``: Value returned by :meth:`.get_context`
* ``renderer``: Value returned by :attr:`.renderer`
.. method:: BaseFormSet.as_p()
Renders the formset with the :attr:`.template_name_p` template.
.. method:: BaseFormSet.as_table()
Renders the formset with the :attr:`.template_name_table` template.
.. method:: BaseFormSet.as_ul()
Renders the formset with the :attr:`.template_name_ul` template.
2019-06-17 14:54:55 +00:00
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::
2008-08-23 22:25:40 +00:00
2015-10-28 01:37:35 +00:00
from django.forms import formset_factory
2015-12-22 15:21:24 +00:00
from django.shortcuts import render
2013-05-19 09:15:35 +00:00
from myapp.forms import ArticleForm
2008-08-23 22:25:40 +00:00
def manage_articles(request):
ArticleFormSet = formset_factory(ArticleForm)
if request.method == 'POST':
formset = ArticleFormSet(request.POST, request.FILES)
if formset.is_valid():
# do something with the formset.cleaned_data
2010-12-13 19:37:18 +00:00
pass
2008-08-23 22:25:40 +00:00
else:
formset = ArticleFormSet()
2015-12-22 15:21:24 +00:00
return render(request, 'manage_articles.html', {'formset': formset})
2008-08-23 22:25:40 +00:00
2008-09-09 01:54:20 +00:00
The ``manage_articles.html`` template might look like this:
.. code-block:: html+django
2008-08-23 22:25:40 +00:00
2018-05-02 13:20:04 +00:00
<form method="post">
2008-08-23 22:25:40 +00:00
{{ formset.management_form }}
<table>
2010-12-19 13:41:43 +00:00
{% for form in formset %}
2008-08-23 22:25:40 +00:00
{{ form }}
{% endfor %}
</table>
</form>
2014-03-01 02:03:46 +00:00
However there's a slight shortcut for the above by letting the formset itself
deal with the management form:
2008-09-09 01:54:20 +00:00
.. code-block:: html+django
2008-08-23 22:25:40 +00:00
2018-05-02 13:20:04 +00:00
<form method="post">
2008-08-23 22:25:40 +00:00
<table>
{{ formset }}
</table>
</form>
2021-09-10 07:06:01 +00:00
The above ends up calling the :meth:`BaseFormSet.render` method on the formset
class. This renders the formset using the template specified by the
:attr:`~BaseFormSet.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
:ref:`overriding the default template <overriding-built-in-formset-templates>`.
2011-06-17 15:39:28 +00:00
.. _manually-rendered-can-delete-and-can-order:
Manually rendered ``can_delete`` and ``can_order``
2016-01-03 10:56:22 +00:00
--------------------------------------------------
2011-06-17 15:39:28 +00:00
If you manually render fields in the template, you can render
``can_delete`` parameter with ``{{ form.DELETE }}``:
.. code-block:: html+django
2018-05-02 13:20:04 +00:00
<form method="post">
2011-06-17 15:39:28 +00:00
{{ formset.management_form }}
{% for form in formset %}
<ul>
<li>{{ form.title }}</li>
2014-12-05 15:23:14 +00:00
<li>{{ form.pub_date }}</li>
2011-06-17 15:39:28 +00:00
{% if formset.can_delete %}
<li>{{ form.DELETE }}</li>
2011-06-18 08:48:25 +00:00
{% endif %}
2011-06-17 15:39:28 +00:00
</ul>
{% endfor %}
</form>
2013-07-08 16:08:30 +00:00
Similarly, if the formset has the ability to order (``can_order=True``), it is
possible to render it with ``{{ form.ORDER }}``.
2011-06-17 15:39:28 +00:00
2017-11-01 19:40:49 +00:00
.. _multiple-formsets-in-view:
2008-08-27 16:44:52 +00:00
Using more than one formset in a view
2016-01-03 10:56:22 +00:00
-------------------------------------
2008-08-27 16:44:52 +00:00
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
2019-01-14 23:54:15 +00:00
more than one formset to be sent to a view without name clashing. Let's take
2014-08-18 14:30:44 +00:00
a look at how this might be accomplished::
2008-08-27 16:44:52 +00:00
2015-10-28 01:37:35 +00:00
from django.forms import formset_factory
2015-12-22 15:21:24 +00:00
from django.shortcuts import render
2013-05-19 09:15:35 +00:00
from myapp.forms import ArticleForm, BookForm
2008-08-27 16:44:52 +00:00
def manage_articles(request):
ArticleFormSet = formset_factory(ArticleForm)
BookFormSet = formset_factory(BookForm)
if request.method == 'POST':
article_formset = ArticleFormSet(request.POST, request.FILES, prefix='articles')
book_formset = BookFormSet(request.POST, request.FILES, prefix='books')
if article_formset.is_valid() and book_formset.is_valid():
# do something with the cleaned_data on the formsets.
2010-12-13 19:37:18 +00:00
pass
2008-08-27 16:44:52 +00:00
else:
article_formset = ArticleFormSet(prefix='articles')
book_formset = BookFormSet(prefix='books')
2015-12-22 15:21:24 +00:00
return render(request, 'manage_articles.html', {
2008-08-27 16:44:52 +00:00
'article_formset': article_formset,
'book_formset': book_formset,
})
You would then render the formsets as normal. It is important to point out
that you need to pass ``prefix`` on both the POST and non-POST cases so that
it is rendered and processed correctly.
2017-11-01 19:40:49 +00:00
Each formset's :ref:`prefix <formset-prefix>` replaces the default ``form``
prefix that's added to each field's ``name`` and ``id`` HTML attributes.