2010-01-05 11:56:19 +08:00
|
|
|
from django.core.exceptions import ValidationError
|
2011-10-17 21:15:40 +08:00
|
|
|
from django.forms import Form
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.forms.fields import BooleanField, IntegerField
|
2021-09-10 15:06:01 +08:00
|
|
|
from django.forms.renderers import get_default_renderer
|
|
|
|
from django.forms.utils import ErrorList, RenderableFormMixin
|
2021-08-03 18:27:22 +08:00
|
|
|
from django.forms.widgets import CheckboxInput, HiddenInput, NumberInput
|
2013-06-22 15:25:14 +08:00
|
|
|
from django.utils.functional import cached_property
|
2020-11-05 17:40:41 +08:00
|
|
|
from django.utils.translation import gettext_lazy as _, ngettext
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2013-11-22 18:23:12 +08:00
|
|
|
__all__ = ('BaseFormSet', 'formset_factory', 'all_valid')
|
2008-07-19 07:54:34 +08:00
|
|
|
|
|
|
|
# special field names
|
|
|
|
TOTAL_FORM_COUNT = 'TOTAL_FORMS'
|
|
|
|
INITIAL_FORM_COUNT = 'INITIAL_FORMS'
|
2013-05-24 14:02:07 +08:00
|
|
|
MIN_NUM_FORM_COUNT = 'MIN_NUM_FORMS'
|
2010-02-01 22:14:56 +08:00
|
|
|
MAX_NUM_FORM_COUNT = 'MAX_NUM_FORMS'
|
2008-07-19 07:54:34 +08:00
|
|
|
ORDERING_FIELD_NAME = 'ORDER'
|
|
|
|
DELETION_FIELD_NAME = 'DELETE'
|
|
|
|
|
2013-05-24 14:02:07 +08:00
|
|
|
# default minimum number of forms in a formset
|
|
|
|
DEFAULT_MIN_NUM = 0
|
|
|
|
|
2013-02-12 18:22:41 +08:00
|
|
|
# default maximum number of forms in a formset, to prevent memory exhaustion
|
|
|
|
DEFAULT_MAX_NUM = 1000
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
class ManagementForm(Form):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Keep track of how many form instances are displayed on the page. If adding
|
|
|
|
new forms via JavaScript, you should increment the count field of this form
|
|
|
|
as well.
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
|
|
|
|
self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
|
2013-05-24 14:02:07 +08:00
|
|
|
# MIN_NUM_FORM_COUNT and MAX_NUM_FORM_COUNT are output with the rest of
|
|
|
|
# the management form, but only for the convenience of client-side
|
|
|
|
# code. The POST value of them returned from the client is not checked.
|
|
|
|
self.base_fields[MIN_NUM_FORM_COUNT] = IntegerField(required=False, widget=HiddenInput)
|
2010-03-28 07:03:56 +08:00
|
|
|
self.base_fields[MAX_NUM_FORM_COUNT] = IntegerField(required=False, widget=HiddenInput)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2020-11-05 17:40:41 +08:00
|
|
|
def clean(self):
|
|
|
|
cleaned_data = super().clean()
|
|
|
|
# When the management form is invalid, we don't know how many forms
|
|
|
|
# were submitted.
|
|
|
|
cleaned_data.setdefault(TOTAL_FORM_COUNT, 0)
|
|
|
|
cleaned_data.setdefault(INITIAL_FORM_COUNT, 0)
|
|
|
|
return cleaned_data
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2021-09-10 15:06:01 +08:00
|
|
|
class BaseFormSet(RenderableFormMixin):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
A collection of instances of the same Form class.
|
|
|
|
"""
|
2021-08-03 18:27:22 +08:00
|
|
|
deletion_widget = CheckboxInput
|
2018-11-22 04:58:04 +08:00
|
|
|
ordering_widget = NumberInput
|
2020-11-05 17:40:41 +08:00
|
|
|
default_error_messages = {
|
|
|
|
'missing_management_form': _(
|
|
|
|
'ManagementForm data is missing or has been tampered with. Missing fields: '
|
|
|
|
'%(field_names)s. You may need to file a bug report if the issue persists.'
|
|
|
|
),
|
|
|
|
}
|
2021-09-10 15:06:01 +08:00
|
|
|
template_name = 'django/forms/formsets/default.html'
|
|
|
|
template_name_p = 'django/forms/formsets/p.html'
|
|
|
|
template_name_table = 'django/forms/formsets/table.html'
|
|
|
|
template_name_ul = 'django/forms/formsets/ul.html'
|
2018-11-22 04:58:04 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
|
2020-11-05 17:40:41 +08:00
|
|
|
initial=None, error_class=ErrorList, form_kwargs=None,
|
|
|
|
error_messages=None):
|
2008-07-19 07:54:34 +08:00
|
|
|
self.is_bound = data is not None or files is not None
|
2009-03-10 19:19:26 +08:00
|
|
|
self.prefix = prefix or self.get_default_prefix()
|
2008-07-19 07:54:34 +08:00
|
|
|
self.auto_id = auto_id
|
2010-11-22 01:27:01 +08:00
|
|
|
self.data = data or {}
|
|
|
|
self.files = files or {}
|
2008-07-19 07:54:34 +08:00
|
|
|
self.initial = initial
|
2015-06-04 18:47:43 +08:00
|
|
|
self.form_kwargs = form_kwargs or {}
|
2008-07-19 07:54:34 +08:00
|
|
|
self.error_class = error_class
|
|
|
|
self._errors = None
|
|
|
|
self._non_form_errors = None
|
|
|
|
|
2020-11-05 17:40:41 +08:00
|
|
|
messages = {}
|
|
|
|
for cls in reversed(type(self).__mro__):
|
|
|
|
messages.update(getattr(cls, 'default_error_messages', {}))
|
|
|
|
if error_messages is not None:
|
|
|
|
messages.update(error_messages)
|
|
|
|
self.error_messages = messages
|
|
|
|
|
2010-12-19 21:41:43 +08:00
|
|
|
def __iter__(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Yield the forms in the order they should be rendered."""
|
2010-12-19 21:41:43 +08:00
|
|
|
return iter(self.forms)
|
|
|
|
|
|
|
|
def __getitem__(self, index):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return the form at the given index, based on the rendering order."""
|
2011-09-10 09:53:56 +08:00
|
|
|
return self.forms[index]
|
2010-12-19 21:41:43 +08:00
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(self.forms)
|
|
|
|
|
2012-08-08 20:52:21 +08:00
|
|
|
def __bool__(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""
|
|
|
|
Return True since all formsets have a management form which is not
|
|
|
|
included in the length.
|
|
|
|
"""
|
2011-09-10 08:05:48 +08:00
|
|
|
return True
|
2012-11-04 04:43:11 +08:00
|
|
|
|
2016-12-02 03:17:25 +08:00
|
|
|
@cached_property
|
2012-09-07 05:07:14 +08:00
|
|
|
def management_form(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return the ManagementForm instance for this FormSet."""
|
2010-11-22 01:27:01 +08:00
|
|
|
if self.is_bound:
|
2021-09-10 15:06:01 +08:00
|
|
|
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix, renderer=self.renderer)
|
2020-11-05 17:40:41 +08:00
|
|
|
form.full_clean()
|
2009-03-30 23:58:52 +08:00
|
|
|
else:
|
2021-09-10 15:06:01 +08:00
|
|
|
form = ManagementForm(
|
|
|
|
auto_id=self.auto_id,
|
|
|
|
prefix=self.prefix,
|
|
|
|
initial={
|
|
|
|
TOTAL_FORM_COUNT: self.total_form_count(),
|
|
|
|
INITIAL_FORM_COUNT: self.initial_form_count(),
|
|
|
|
MIN_NUM_FORM_COUNT: self.min_num,
|
|
|
|
MAX_NUM_FORM_COUNT: self.max_num,
|
|
|
|
},
|
|
|
|
renderer=self.renderer,
|
|
|
|
)
|
2009-03-30 23:58:52 +08:00
|
|
|
return form
|
|
|
|
|
|
|
|
def total_form_count(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return the total number of forms in this FormSet."""
|
2010-11-22 01:27:01 +08:00
|
|
|
if self.is_bound:
|
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 14:27:06 +08:00
|
|
|
# return absolute_max if it is lower than the actual total form
|
|
|
|
# count in the data; this is DoS protection to prevent clients
|
|
|
|
# from forcing the server to instantiate arbitrary numbers of
|
|
|
|
# forms
|
|
|
|
return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max)
|
2009-03-30 23:58:52 +08:00
|
|
|
else:
|
2010-03-28 07:03:56 +08:00
|
|
|
initial_forms = self.initial_form_count()
|
2014-05-16 11:12:32 +08:00
|
|
|
total_forms = max(initial_forms, self.min_num) + self.extra
|
2010-03-28 07:03:56 +08:00
|
|
|
# Allow all existing related objects/inlines to be displayed,
|
|
|
|
# but don't allow extra beyond max_num.
|
2013-02-12 18:22:41 +08:00
|
|
|
if initial_forms > self.max_num >= 0:
|
|
|
|
total_forms = initial_forms
|
|
|
|
elif total_forms > self.max_num >= 0:
|
|
|
|
total_forms = self.max_num
|
2009-03-30 23:58:52 +08:00
|
|
|
return total_forms
|
|
|
|
|
|
|
|
def initial_form_count(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return the number of forms that are required in this FormSet."""
|
2010-11-22 01:27:01 +08:00
|
|
|
if self.is_bound:
|
2009-03-30 23:58:52 +08:00
|
|
|
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
|
|
|
|
else:
|
2013-03-29 01:16:53 +08:00
|
|
|
# Use the length of the initial data if it's there, 0 otherwise.
|
2013-05-17 22:33:36 +08:00
|
|
|
initial_forms = len(self.initial) if self.initial else 0
|
2009-03-30 23:58:52 +08:00
|
|
|
return initial_forms
|
|
|
|
|
2013-06-22 15:25:14 +08:00
|
|
|
@cached_property
|
|
|
|
def forms(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Instantiate forms at first property access."""
|
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 14:27:06 +08:00
|
|
|
# DoS protection is included in total_form_count()
|
2019-04-24 19:09:29 +08:00
|
|
|
return [
|
|
|
|
self._construct_form(i, **self.get_form_kwargs(i))
|
|
|
|
for i in range(self.total_form_count())
|
|
|
|
]
|
2009-03-10 19:19:26 +08:00
|
|
|
|
2015-06-04 18:47:43 +08:00
|
|
|
def get_form_kwargs(self, index):
|
|
|
|
"""
|
|
|
|
Return additional keyword arguments for each individual formset form.
|
2015-06-05 18:42:58 +08:00
|
|
|
|
|
|
|
index will be None if the form being constructed is a new empty
|
|
|
|
form.
|
2015-06-04 18:47:43 +08:00
|
|
|
"""
|
|
|
|
return self.form_kwargs.copy()
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def _construct_form(self, i, **kwargs):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Instantiate and return the i-th form instance in a formset."""
|
2012-10-04 21:24:23 +08:00
|
|
|
defaults = {
|
|
|
|
'auto_id': self.auto_id,
|
|
|
|
'prefix': self.add_prefix(i),
|
|
|
|
'error_class': self.error_class,
|
2016-03-29 02:02:04 +08:00
|
|
|
# Don't render the HTML 'required' attribute as it may cause
|
|
|
|
# incorrect validation for extra, optional, and deleted
|
|
|
|
# forms in the formset.
|
|
|
|
'use_required_attribute': False,
|
2021-09-10 15:06:01 +08:00
|
|
|
'renderer': self.renderer,
|
2013-10-18 17:02:43 +08:00
|
|
|
}
|
2010-11-22 01:27:01 +08:00
|
|
|
if self.is_bound:
|
2008-07-19 07:54:34 +08:00
|
|
|
defaults['data'] = self.data
|
|
|
|
defaults['files'] = self.files
|
2014-03-31 03:11:05 +08:00
|
|
|
if self.initial and 'initial' not in kwargs:
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2008-07-19 07:54:34 +08:00
|
|
|
defaults['initial'] = self.initial[i]
|
2017-09-07 20:16:21 +08:00
|
|
|
except IndexError:
|
|
|
|
pass
|
2014-05-16 11:12:32 +08:00
|
|
|
# Allow extra forms to be empty, unless they're part of
|
|
|
|
# the minimum forms.
|
|
|
|
if i >= self.initial_form_count() and i >= self.min_num:
|
2008-07-19 07:54:34 +08:00
|
|
|
defaults['empty_permitted'] = True
|
|
|
|
defaults.update(kwargs)
|
|
|
|
form = self.form(**defaults)
|
|
|
|
self.add_fields(form, i)
|
|
|
|
return form
|
|
|
|
|
2012-09-07 05:07:14 +08:00
|
|
|
@property
|
|
|
|
def initial_forms(self):
|
2009-03-30 23:58:52 +08:00
|
|
|
"""Return a list of all the initial forms in this formset."""
|
|
|
|
return self.forms[:self.initial_form_count()]
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2012-09-07 05:07:14 +08:00
|
|
|
@property
|
|
|
|
def extra_forms(self):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""Return a list of all the extra forms in this formset."""
|
2009-03-30 23:58:52 +08:00
|
|
|
return self.forms[self.initial_form_count():]
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2012-09-07 05:07:14 +08:00
|
|
|
@property
|
2013-01-02 03:50:13 +08:00
|
|
|
def empty_form(self):
|
|
|
|
form = self.form(
|
|
|
|
auto_id=self.auto_id,
|
|
|
|
prefix=self.add_prefix('__prefix__'),
|
|
|
|
empty_permitted=True,
|
2016-03-29 02:02:04 +08:00
|
|
|
use_required_attribute=False,
|
2021-09-10 15:06:01 +08:00
|
|
|
**self.get_form_kwargs(None),
|
|
|
|
renderer=self.renderer,
|
2013-01-02 03:50:13 +08:00
|
|
|
)
|
2010-01-26 23:02:53 +08:00
|
|
|
self.add_fields(form, None)
|
|
|
|
return form
|
|
|
|
|
2012-09-07 05:07:14 +08:00
|
|
|
@property
|
|
|
|
def cleaned_data(self):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return a list of form.cleaned_data dicts for every form in self.forms.
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
if not self.is_valid():
|
|
|
|
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
|
|
|
|
return [form.cleaned_data for form in self.forms]
|
|
|
|
|
2012-09-07 05:07:14 +08:00
|
|
|
@property
|
|
|
|
def deleted_forms(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return a list of forms that have been marked for deletion."""
|
2008-07-19 07:54:34 +08:00
|
|
|
if not self.is_valid() or not self.can_delete:
|
2013-02-09 04:30:06 +08:00
|
|
|
return []
|
2008-07-19 07:54:34 +08:00
|
|
|
# construct _deleted_form_indexes which is just a list of form indexes
|
|
|
|
# that have had their deletion widget set to True
|
|
|
|
if not hasattr(self, '_deleted_form_indexes'):
|
|
|
|
self._deleted_form_indexes = []
|
2020-10-26 15:02:38 +08:00
|
|
|
for i, form in enumerate(self.forms):
|
2008-07-19 07:54:34 +08:00
|
|
|
# if this is an extra form and hasn't changed, don't consider it
|
2009-03-30 23:58:52 +08:00
|
|
|
if i >= self.initial_form_count() and not form.has_changed():
|
2008-07-19 07:54:34 +08:00
|
|
|
continue
|
2010-03-12 23:51:00 +08:00
|
|
|
if self._should_delete_form(form):
|
2008-07-19 07:54:34 +08:00
|
|
|
self._deleted_form_indexes.append(i)
|
|
|
|
return [self.forms[i] for i in self._deleted_form_indexes]
|
|
|
|
|
2012-09-07 05:07:14 +08:00
|
|
|
@property
|
|
|
|
def ordered_forms(self):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return a list of form in the order specified by the incoming data.
|
|
|
|
Raise an AttributeError if ordering is not allowed.
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
if not self.is_valid() or not self.can_order:
|
|
|
|
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
|
|
|
|
# Construct _ordering, which is a list of (form_index, order_field_value)
|
|
|
|
# tuples. After constructing this list, we'll sort it by order_field_value
|
|
|
|
# so we have a way to get to the form indexes in the order specified
|
|
|
|
# by the form data.
|
|
|
|
if not hasattr(self, '_ordering'):
|
|
|
|
self._ordering = []
|
2020-10-26 15:02:38 +08:00
|
|
|
for i, form in enumerate(self.forms):
|
2008-07-19 07:54:34 +08:00
|
|
|
# if this is an extra form and hasn't changed, don't consider it
|
2009-03-30 23:58:52 +08:00
|
|
|
if i >= self.initial_form_count() and not form.has_changed():
|
2008-07-19 07:54:34 +08:00
|
|
|
continue
|
|
|
|
# don't add data marked for deletion to self.ordered_data
|
2010-03-12 23:51:00 +08:00
|
|
|
if self.can_delete and self._should_delete_form(form):
|
2008-07-19 07:54:34 +08:00
|
|
|
continue
|
|
|
|
self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
|
|
|
|
# After we're done populating self._ordering, sort it.
|
2009-04-28 22:17:18 +08:00
|
|
|
# A sort function to order things numerically ascending, but
|
|
|
|
# None should be sorted below anything else. Allowing None as
|
|
|
|
# a comparison value makes it so we can leave ordering fields
|
2010-08-07 00:31:44 +08:00
|
|
|
# blank.
|
2013-10-22 18:21:07 +08:00
|
|
|
|
2010-08-07 00:31:44 +08:00
|
|
|
def compare_ordering_key(k):
|
|
|
|
if k[1] is None:
|
2013-11-03 03:27:47 +08:00
|
|
|
return (1, 0) # +infinity, larger than any number
|
2010-08-07 00:31:44 +08:00
|
|
|
return (0, k[1])
|
|
|
|
self._ordering.sort(key=compare_ordering_key)
|
2011-08-12 22:14:15 +08:00
|
|
|
# Return a list of form.cleaned_data dicts in the order specified by
|
2008-07-19 07:54:34 +08:00
|
|
|
# the form data.
|
|
|
|
return [self.forms[i[0]] for i in self._ordering]
|
|
|
|
|
2011-05-02 00:46:02 +08:00
|
|
|
@classmethod
|
2009-03-10 19:19:26 +08:00
|
|
|
def get_default_prefix(cls):
|
|
|
|
return 'form'
|
|
|
|
|
2021-08-03 18:27:22 +08:00
|
|
|
@classmethod
|
|
|
|
def get_deletion_widget(cls):
|
|
|
|
return cls.deletion_widget
|
|
|
|
|
2018-11-22 04:58:04 +08:00
|
|
|
@classmethod
|
|
|
|
def get_ordering_widget(cls):
|
|
|
|
return cls.ordering_widget
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def non_form_errors(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return an ErrorList of errors that aren't associated with a particular
|
|
|
|
form -- i.e., from formset.clean(). Return an empty ErrorList if there
|
2008-07-19 07:54:34 +08:00
|
|
|
are none.
|
|
|
|
"""
|
2013-05-18 19:44:27 +08:00
|
|
|
if self._non_form_errors is None:
|
|
|
|
self.full_clean()
|
|
|
|
return self._non_form_errors
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2012-09-07 05:07:14 +08:00
|
|
|
@property
|
|
|
|
def errors(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return a list of form.errors for every form in self.forms."""
|
2008-07-19 07:54:34 +08:00
|
|
|
if self._errors is None:
|
|
|
|
self.full_clean()
|
|
|
|
return self._errors
|
|
|
|
|
2013-06-16 04:34:25 +08:00
|
|
|
def total_error_count(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return the number of errors across all forms in the formset."""
|
2013-06-16 04:34:25 +08:00
|
|
|
return len(self.non_form_errors()) +\
|
|
|
|
sum(len(form_errors) for form_errors in self.errors)
|
|
|
|
|
2010-03-12 23:51:00 +08:00
|
|
|
def _should_delete_form(self, form):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return whether or not the form was marked for deletion."""
|
2012-08-30 21:51:13 +08:00
|
|
|
return form.cleaned_data.get(DELETION_FIELD_NAME, False)
|
2010-03-12 23:51:00 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def is_valid(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return True if every form in self.forms is valid."""
|
2008-07-19 07:54:34 +08:00
|
|
|
if not self.is_bound:
|
|
|
|
return False
|
2020-11-03 16:57:10 +08:00
|
|
|
# Accessing errors triggers a full clean the first time only.
|
2013-09-07 12:56:40 +08:00
|
|
|
self.errors
|
2020-11-03 16:57:10 +08:00
|
|
|
# List comprehension ensures is_valid() is called for all forms.
|
|
|
|
# Forms due to be deleted shouldn't cause the formset to be invalid.
|
|
|
|
forms_valid = all([
|
|
|
|
form.is_valid() for form in self.forms
|
|
|
|
if not (self.can_delete and self._should_delete_form(form))
|
|
|
|
])
|
2014-04-04 15:10:17 +08:00
|
|
|
return forms_valid and not self.non_form_errors()
|
2008-07-19 07:54:34 +08:00
|
|
|
|
|
|
|
def full_clean(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Clean all of self.data and populate self._errors and
|
2013-05-18 19:44:27 +08:00
|
|
|
self._non_form_errors.
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
self._errors = []
|
2021-09-10 15:06:01 +08:00
|
|
|
self._non_form_errors = self.error_class(error_class='nonform', renderer=self.renderer)
|
2016-07-18 22:30:55 +08:00
|
|
|
empty_forms_count = 0
|
2013-05-18 19:44:27 +08:00
|
|
|
|
2013-11-03 03:27:47 +08:00
|
|
|
if not self.is_bound: # Stop further processing.
|
2008-07-19 07:54:34 +08:00
|
|
|
return
|
2020-11-05 17:40:41 +08:00
|
|
|
|
|
|
|
if not self.management_form.is_valid():
|
|
|
|
error = ValidationError(
|
|
|
|
self.error_messages['missing_management_form'],
|
|
|
|
params={
|
|
|
|
'field_names': ', '.join(
|
|
|
|
self.management_form.add_prefix(field_name)
|
|
|
|
for field_name in self.management_form.errors
|
|
|
|
),
|
|
|
|
},
|
|
|
|
code='missing_management_form',
|
|
|
|
)
|
|
|
|
self._non_form_errors.append(error)
|
|
|
|
|
2020-10-26 15:02:38 +08:00
|
|
|
for i, form in enumerate(self.forms):
|
2017-04-28 21:32:40 +08:00
|
|
|
# Empty forms are unchanged forms beyond those with initial data.
|
|
|
|
if not form.has_changed() and i >= self.initial_form_count():
|
2016-07-18 22:30:55 +08:00
|
|
|
empty_forms_count += 1
|
2017-07-25 06:55:41 +08:00
|
|
|
# Accessing errors calls full_clean() if necessary.
|
|
|
|
# _should_delete_form() requires cleaned_data.
|
|
|
|
form_errors = form.errors
|
|
|
|
if self.can_delete and self._should_delete_form(form):
|
|
|
|
continue
|
|
|
|
self._errors.append(form_errors)
|
2008-07-19 07:54:34 +08:00
|
|
|
try:
|
2013-05-21 00:13:03 +08:00
|
|
|
if (self.validate_max and
|
2013-11-26 17:43:46 +08:00
|
|
|
self.total_form_count() - len(self.deleted_forms) > self.max_num) or \
|
|
|
|
self.management_form.cleaned_data[TOTAL_FORM_COUNT] > self.absolute_max:
|
2017-01-27 03:58:33 +08:00
|
|
|
raise ValidationError(ngettext(
|
2020-09-24 04:08:15 +08:00
|
|
|
"Please submit at most %d form.",
|
|
|
|
"Please submit at most %d forms.", self.max_num) % self.max_num,
|
2013-06-06 02:55:05 +08:00
|
|
|
code='too_many_forms',
|
|
|
|
)
|
2013-05-24 14:02:07 +08:00
|
|
|
if (self.validate_min and
|
2016-07-18 22:30:55 +08:00
|
|
|
self.total_form_count() - len(self.deleted_forms) - empty_forms_count < self.min_num):
|
2017-01-27 03:58:33 +08:00
|
|
|
raise ValidationError(ngettext(
|
2020-09-24 04:08:15 +08:00
|
|
|
"Please submit at least %d form.",
|
|
|
|
"Please submit at least %d forms.", self.min_num) % self.min_num,
|
2013-05-24 14:02:07 +08:00
|
|
|
code='too_few_forms')
|
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 14:27:06 +08:00
|
|
|
# Give self.clean() a chance to do cross-form validation.
|
2008-07-19 07:54:34 +08:00
|
|
|
self.clean()
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2021-07-08 04:50:30 +08:00
|
|
|
self._non_form_errors = self.error_class(
|
|
|
|
e.error_list,
|
2021-09-10 15:06:01 +08:00
|
|
|
error_class='nonform',
|
|
|
|
renderer=self.renderer,
|
2021-07-08 04:50:30 +08:00
|
|
|
)
|
2008-07-19 07:54:34 +08:00
|
|
|
|
|
|
|
def clean(self):
|
|
|
|
"""
|
|
|
|
Hook for doing any extra formset-wide cleaning after Form.clean() has
|
|
|
|
been called on every form. Any ValidationError raised by this method
|
2014-03-02 22:25:53 +08:00
|
|
|
will not be associated with a particular form; it will be accessible
|
2008-07-19 07:54:34 +08:00
|
|
|
via formset.non_form_errors()
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
2011-09-10 10:42:05 +08:00
|
|
|
def has_changed(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return True if data in any form differs from initial."""
|
2011-09-10 10:42:05 +08:00
|
|
|
return any(form.has_changed() for form in self)
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def add_fields(self, form, index):
|
|
|
|
"""A hook for adding extra fields on to each form instance."""
|
2020-06-20 05:46:25 +08:00
|
|
|
initial_form_count = self.initial_form_count()
|
2008-07-19 07:54:34 +08:00
|
|
|
if self.can_order:
|
|
|
|
# Only pre-fill the ordering field for initial forms.
|
2020-06-20 05:46:25 +08:00
|
|
|
if index is not None and index < initial_form_count:
|
2018-11-22 04:58:04 +08:00
|
|
|
form.fields[ORDERING_FIELD_NAME] = IntegerField(
|
|
|
|
label=_('Order'),
|
|
|
|
initial=index + 1,
|
|
|
|
required=False,
|
|
|
|
widget=self.get_ordering_widget(),
|
|
|
|
)
|
2008-07-19 07:54:34 +08:00
|
|
|
else:
|
2018-11-22 04:58:04 +08:00
|
|
|
form.fields[ORDERING_FIELD_NAME] = IntegerField(
|
|
|
|
label=_('Order'),
|
|
|
|
required=False,
|
|
|
|
widget=self.get_ordering_widget(),
|
|
|
|
)
|
2020-06-20 05:46:25 +08:00
|
|
|
if self.can_delete and (self.can_delete_extra or index < initial_form_count):
|
2021-08-03 18:27:22 +08:00
|
|
|
form.fields[DELETION_FIELD_NAME] = BooleanField(
|
|
|
|
label=_('Delete'),
|
|
|
|
required=False,
|
|
|
|
widget=self.get_deletion_widget(),
|
|
|
|
)
|
2008-07-19 07:54:34 +08:00
|
|
|
|
|
|
|
def add_prefix(self, index):
|
|
|
|
return '%s-%s' % (self.prefix, index)
|
|
|
|
|
|
|
|
def is_multipart(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return True if the formset needs to be multipart, i.e. it
|
|
|
|
has FileInput, or False otherwise.
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
2013-01-03 22:13:51 +08:00
|
|
|
if self.forms:
|
|
|
|
return self.forms[0].is_multipart()
|
|
|
|
else:
|
|
|
|
return self.empty_form.is_multipart()
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2012-09-07 05:07:14 +08:00
|
|
|
@property
|
|
|
|
def media(self):
|
2008-07-19 07:54:34 +08:00
|
|
|
# All the forms on a FormSet are the same, so you only need to
|
|
|
|
# interrogate the first form for media.
|
|
|
|
if self.forms:
|
|
|
|
return self.forms[0].media
|
|
|
|
else:
|
2013-01-03 22:13:51 +08:00
|
|
|
return self.empty_form.media
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2021-09-10 15:06:01 +08:00
|
|
|
def get_context(self):
|
|
|
|
return {'formset': self}
|
2010-10-18 12:44:49 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
|
2013-05-24 14:02:07 +08:00
|
|
|
can_delete=False, max_num=None, validate_max=False,
|
2020-06-20 05:46:25 +08:00
|
|
|
min_num=None, validate_min=False, absolute_max=None,
|
2021-09-10 15:06:01 +08:00
|
|
|
can_delete_extra=True, renderer=None):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""Return a FormSet for the given form class."""
|
2013-05-24 14:02:07 +08:00
|
|
|
if min_num is None:
|
|
|
|
min_num = DEFAULT_MIN_NUM
|
2013-02-12 18:22:41 +08:00
|
|
|
if max_num is None:
|
|
|
|
max_num = DEFAULT_MAX_NUM
|
2020-04-30 15:34:53 +08:00
|
|
|
# absolute_max is a hard limit on forms instantiated, to prevent
|
|
|
|
# memory-exhaustion attacks. Default to max_num + DEFAULT_MAX_NUM
|
|
|
|
# (which is 2 * DEFAULT_MAX_NUM if max_num is None in the first place).
|
|
|
|
if absolute_max is None:
|
|
|
|
absolute_max = max_num + DEFAULT_MAX_NUM
|
|
|
|
if max_num > absolute_max:
|
|
|
|
raise ValueError(
|
|
|
|
"'absolute_max' must be greater or equal to 'max_num'."
|
|
|
|
)
|
2019-01-03 07:18:19 +08:00
|
|
|
attrs = {
|
|
|
|
'form': form,
|
|
|
|
'extra': extra,
|
|
|
|
'can_order': can_order,
|
|
|
|
'can_delete': can_delete,
|
2020-06-20 05:46:25 +08:00
|
|
|
'can_delete_extra': can_delete_extra,
|
2019-01-03 07:18:19 +08:00
|
|
|
'min_num': min_num,
|
|
|
|
'max_num': max_num,
|
|
|
|
'absolute_max': absolute_max,
|
|
|
|
'validate_min': validate_min,
|
|
|
|
'validate_max': validate_max,
|
2021-09-10 15:06:01 +08:00
|
|
|
'renderer': renderer or get_default_renderer(),
|
2019-01-03 07:18:19 +08:00
|
|
|
}
|
2017-01-19 22:48:01 +08:00
|
|
|
return type(form.__name__ + 'FormSet', (formset,), attrs)
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def all_valid(formsets):
|
2018-02-05 23:29:38 +08:00
|
|
|
"""Validate every formset and return True if all are valid."""
|
2020-11-03 16:57:10 +08:00
|
|
|
# List comprehension ensures is_valid() is called for all formsets.
|
|
|
|
return all([formset.is_valid() for formset in formsets])
|