2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Form classes
|
|
|
|
"""
|
|
|
|
|
2011-03-28 10:11:19 +08:00
|
|
|
import copy
|
2011-10-18 00:39:53 +08:00
|
|
|
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
|
2011-10-18 00:39:53 +08:00
|
|
|
from django.forms.fields import Field, FileField
|
2019-07-18 14:13:01 +08:00
|
|
|
from django.forms.utils import ErrorDict, ErrorList
|
2015-09-09 21:09:59 +08:00
|
|
|
from django.forms.widgets import Media, MediaDefiningClass
|
2019-03-05 23:41:08 +08:00
|
|
|
from django.utils.datastructures import MultiValueDict
|
2015-08-04 08:14:15 +08:00
|
|
|
from django.utils.functional import cached_property
|
2015-09-09 21:09:59 +08:00
|
|
|
from django.utils.html import conditional_escape, html_safe
|
2007-11-14 20:58:53 +08:00
|
|
|
from django.utils.safestring import mark_safe
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext as _
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2016-12-28 06:00:56 +08:00
|
|
|
from .renderers import get_default_renderer
|
|
|
|
|
2006-12-17 13:11:48 +08:00
|
|
|
__all__ = ('BaseForm', 'Form')
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
class DeclarativeFieldsMetaclass(MediaDefiningClass):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Collect Fields declared on the base classes."""
|
2013-07-21 03:25:27 +08:00
|
|
|
def __new__(mcs, name, bases, attrs):
|
2020-11-02 17:46:56 +08:00
|
|
|
# Collect fields from current class and remove them from attrs.
|
|
|
|
attrs['declared_fields'] = {
|
|
|
|
key: attrs.pop(key) for key, value in list(attrs.items())
|
|
|
|
if isinstance(value, Field)
|
|
|
|
}
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2019-11-28 22:34:29 +08:00
|
|
|
new_class = super().__new__(mcs, name, bases, attrs)
|
2013-07-21 03:25:27 +08:00
|
|
|
|
|
|
|
# Walk through the MRO.
|
2019-02-05 19:22:08 +08:00
|
|
|
declared_fields = {}
|
2013-07-21 03:25:27 +08:00
|
|
|
for base in reversed(new_class.__mro__):
|
|
|
|
# Collect fields from base class.
|
|
|
|
if hasattr(base, 'declared_fields'):
|
|
|
|
declared_fields.update(base.declared_fields)
|
|
|
|
|
2013-10-14 23:42:33 +08:00
|
|
|
# Field shadowing.
|
2014-05-24 17:52:18 +08:00
|
|
|
for attr, value in base.__dict__.items():
|
|
|
|
if value is None and attr in declared_fields:
|
2013-10-14 23:42:33 +08:00
|
|
|
declared_fields.pop(attr)
|
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
new_class.base_fields = declared_fields
|
|
|
|
new_class.declared_fields = declared_fields
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
return new_class
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2015-03-19 04:42:59 +08:00
|
|
|
@html_safe
|
2017-01-19 15:39:46 +08:00
|
|
|
class BaseForm:
|
2017-01-25 05:23:56 +08:00
|
|
|
"""
|
|
|
|
The main implementation of all the Form logic. Note that this class is
|
|
|
|
different than Form. See the comments by the Form class for more info. Any
|
|
|
|
improvements to the form API should be made to this class, not to the Form
|
|
|
|
class.
|
|
|
|
"""
|
2016-12-28 06:00:56 +08:00
|
|
|
default_renderer = None
|
2015-03-16 08:33:59 +08:00
|
|
|
field_order = None
|
2015-05-25 02:43:20 +08:00
|
|
|
prefix = None
|
2016-03-29 02:02:04 +08:00
|
|
|
use_required_attribute = True
|
2015-03-16 08:33:59 +08:00
|
|
|
|
2007-09-14 07:09:40 +08:00
|
|
|
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
|
2013-07-13 17:43:14 +08:00
|
|
|
initial=None, error_class=ErrorList, label_suffix=None,
|
2016-12-28 06:00:56 +08:00
|
|
|
empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None):
|
2007-08-06 21:58:56 +08:00
|
|
|
self.is_bound = data is not None or files is not None
|
2019-03-05 23:41:08 +08:00
|
|
|
self.data = MultiValueDict() if data is None else data
|
|
|
|
self.files = MultiValueDict() if files is None else files
|
2006-11-16 07:09:10 +08:00
|
|
|
self.auto_id = auto_id
|
2015-05-25 02:43:20 +08:00
|
|
|
if prefix is not None:
|
|
|
|
self.prefix = prefix
|
2007-01-09 12:39:44 +08:00
|
|
|
self.initial = initial or {}
|
2007-09-14 07:09:40 +08:00
|
|
|
self.error_class = error_class
|
2013-07-13 17:43:14 +08:00
|
|
|
# Translators: This is the default suffix added to form field labels
|
|
|
|
self.label_suffix = label_suffix if label_suffix is not None else _(':')
|
2008-07-19 07:54:34 +08:00
|
|
|
self.empty_permitted = empty_permitted
|
2013-11-03 03:27:47 +08:00
|
|
|
self._errors = None # Stores the errors after clean() has been called.
|
2007-02-15 11:46:43 +08:00
|
|
|
|
2007-01-28 06:06:56 +08:00
|
|
|
# The base_fields class attribute is the *class-wide* definition of
|
|
|
|
# fields. Because a particular *instance* of the class might want to
|
|
|
|
# alter self.fields, we create self.fields here by copying base_fields.
|
|
|
|
# Instances should always modify self.fields; they should not modify
|
|
|
|
# self.base_fields.
|
2011-03-28 10:11:19 +08:00
|
|
|
self.fields = copy.deepcopy(self.base_fields)
|
2015-02-23 11:06:41 +08:00
|
|
|
self._bound_fields_cache = {}
|
2015-03-16 08:33:59 +08:00
|
|
|
self.order_fields(self.field_order if field_order is None else field_order)
|
|
|
|
|
2016-03-29 02:02:04 +08:00
|
|
|
if use_required_attribute is not None:
|
|
|
|
self.use_required_attribute = use_required_attribute
|
|
|
|
|
2018-02-12 20:45:37 +08:00
|
|
|
if self.empty_permitted and self.use_required_attribute:
|
|
|
|
raise ValueError(
|
|
|
|
'The empty_permitted and use_required_attribute arguments may '
|
|
|
|
'not both be True.'
|
|
|
|
)
|
|
|
|
|
2016-12-28 06:00:56 +08:00
|
|
|
# Initialize form renderer. Use a global default if not specified
|
|
|
|
# either as an argument or as self.default_renderer.
|
|
|
|
if renderer is None:
|
|
|
|
if self.default_renderer is None:
|
|
|
|
renderer = get_default_renderer()
|
|
|
|
else:
|
|
|
|
renderer = self.default_renderer
|
|
|
|
if isinstance(self.default_renderer, type):
|
|
|
|
renderer = renderer()
|
|
|
|
self.renderer = renderer
|
|
|
|
|
2015-03-16 08:33:59 +08:00
|
|
|
def order_fields(self, field_order):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Rearrange the fields according to field_order.
|
|
|
|
|
|
|
|
field_order is a list of field names specifying the order. Append fields
|
|
|
|
not included in the list in the default order for backward compatibility
|
|
|
|
with subclasses not overriding field_order. If field_order is None,
|
|
|
|
keep all fields in the order defined in the class. Ignore unknown
|
|
|
|
fields in field_order to allow disabling fields in form subclasses
|
|
|
|
without redefining ordering.
|
2015-03-16 08:33:59 +08:00
|
|
|
"""
|
|
|
|
if field_order is None:
|
|
|
|
return
|
2019-02-05 19:22:08 +08:00
|
|
|
fields = {}
|
2015-03-16 08:33:59 +08:00
|
|
|
for key in field_order:
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2015-03-16 08:33:59 +08:00
|
|
|
fields[key] = self.fields.pop(key)
|
2017-09-07 20:16:21 +08:00
|
|
|
except KeyError: # ignore unknown fields
|
|
|
|
pass
|
2015-03-16 08:33:59 +08:00
|
|
|
fields.update(self.fields) # add remaining fields in original order
|
|
|
|
self.fields = fields
|
2006-11-05 04:49:59 +08:00
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
def __str__(self):
|
2006-11-05 04:49:59 +08:00
|
|
|
return self.as_table()
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2014-08-22 01:09:05 +08:00
|
|
|
def __repr__(self):
|
|
|
|
if self._errors is None:
|
|
|
|
is_valid = "Unknown"
|
|
|
|
else:
|
2017-12-08 06:13:07 +08:00
|
|
|
is_valid = self.is_bound and not self._errors
|
2014-08-22 01:09:05 +08:00
|
|
|
return '<%(cls)s bound=%(bound)s, valid=%(valid)s, fields=(%(fields)s)>' % {
|
|
|
|
'cls': self.__class__.__name__,
|
|
|
|
'bound': self.is_bound,
|
|
|
|
'valid': is_valid,
|
|
|
|
'fields': ';'.join(self.fields),
|
|
|
|
}
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
def __iter__(self):
|
2012-01-20 06:05:47 +08:00
|
|
|
for name in self.fields:
|
|
|
|
yield self[name]
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def __getitem__(self, name):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return a BoundField with the given name."""
|
2006-11-05 04:49:59 +08:00
|
|
|
try:
|
|
|
|
field = self.fields[name]
|
|
|
|
except KeyError:
|
2014-05-04 01:02:07 +08:00
|
|
|
raise KeyError(
|
2016-04-14 21:10:33 +08:00
|
|
|
"Key '%s' not found in '%s'. Choices are: %s." % (
|
|
|
|
name,
|
|
|
|
self.__class__.__name__,
|
2019-02-09 22:18:48 +08:00
|
|
|
', '.join(sorted(self.fields)),
|
2016-04-14 21:10:33 +08:00
|
|
|
)
|
|
|
|
)
|
2015-02-23 11:06:41 +08:00
|
|
|
if name not in self._bound_fields_cache:
|
2015-08-10 16:55:49 +08:00
|
|
|
self._bound_fields_cache[name] = field.get_bound_field(self, name)
|
2015-02-23 11:06:41 +08:00
|
|
|
return self._bound_fields_cache[name]
|
2006-11-05 04:49:59 +08:00
|
|
|
|
2013-01-26 05:41:45 +08:00
|
|
|
@property
|
|
|
|
def errors(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return an ErrorDict for the data provided for the form."""
|
2007-05-26 16:53:22 +08:00
|
|
|
if self._errors is None:
|
2006-11-05 04:49:59 +08:00
|
|
|
self.full_clean()
|
2007-05-26 16:53:22 +08:00
|
|
|
return self._errors
|
2006-10-29 04:34:37 +08:00
|
|
|
|
|
|
|
def is_valid(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return True if the form has no errors, or False otherwise."""
|
2014-04-04 15:10:17 +08:00
|
|
|
return self.is_bound and not self.errors
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-12-12 13:55:39 +08:00
|
|
|
def add_prefix(self, field_name):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return the field name with a prefix appended, if this Form has a
|
2006-12-12 13:55:39 +08:00
|
|
|
prefix set.
|
|
|
|
|
|
|
|
Subclasses may wish to override.
|
|
|
|
"""
|
2013-05-27 10:47:50 +08:00
|
|
|
return '%s-%s' % (self.prefix, field_name) if self.prefix else field_name
|
2006-12-12 13:55:39 +08:00
|
|
|
|
2008-09-02 05:28:32 +08:00
|
|
|
def add_initial_prefix(self, field_name):
|
2019-04-14 15:44:56 +08:00
|
|
|
"""Add an 'initial' prefix for checking dynamic initial values."""
|
2012-06-08 00:08:47 +08:00
|
|
|
return 'initial-%s' % self.add_prefix(field_name)
|
2008-09-02 05:28:32 +08:00
|
|
|
|
2007-01-29 06:10:04 +08:00
|
|
|
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
|
2017-01-25 05:23:56 +08:00
|
|
|
"Output HTML. Used by as_table(), as_ul(), as_p()."
|
2020-02-11 05:40:07 +08:00
|
|
|
# Errors that should be displayed above all fields.
|
|
|
|
top_errors = self.non_field_errors().copy()
|
2006-12-07 14:06:58 +08:00
|
|
|
output, hidden_fields = [], []
|
2009-12-13 02:52:12 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
for name, field in self.fields.items():
|
2010-01-10 06:51:03 +08:00
|
|
|
html_class_attr = ''
|
2012-01-20 06:05:47 +08:00
|
|
|
bf = self[name]
|
2017-12-11 20:30:47 +08:00
|
|
|
bf_errors = self.error_class(bf.errors)
|
2006-12-01 01:07:40 +08:00
|
|
|
if bf.is_hidden:
|
2006-12-07 13:35:39 +08:00
|
|
|
if bf_errors:
|
2013-01-27 02:57:10 +08:00
|
|
|
top_errors.extend(
|
2017-04-22 01:52:26 +08:00
|
|
|
[_('(Hidden field %(name)s) %(error)s') % {'name': name, 'error': str(e)}
|
2013-01-27 02:57:10 +08:00
|
|
|
for e in bf_errors])
|
2016-12-29 23:27:49 +08:00
|
|
|
hidden_fields.append(str(bf))
|
2006-12-01 01:07:40 +08:00
|
|
|
else:
|
2014-03-02 22:25:53 +08:00
|
|
|
# Create a 'class="..."' attribute if the row should have any
|
2009-12-13 02:52:12 +08:00
|
|
|
# CSS classes applied.
|
|
|
|
css_classes = bf.css_classes()
|
|
|
|
if css_classes:
|
|
|
|
html_class_attr = ' class="%s"' % css_classes
|
|
|
|
|
2006-12-07 23:49:05 +08:00
|
|
|
if errors_on_separate_row and bf_errors:
|
2017-04-22 01:52:26 +08:00
|
|
|
output.append(error_row % str(bf_errors))
|
2009-12-13 02:52:12 +08:00
|
|
|
|
2007-04-27 22:27:07 +08:00
|
|
|
if bf.label:
|
2017-04-22 01:52:26 +08:00
|
|
|
label = conditional_escape(bf.label)
|
2007-04-27 22:27:07 +08:00
|
|
|
label = bf.label_tag(label) or ''
|
|
|
|
else:
|
|
|
|
label = ''
|
2009-12-13 02:52:12 +08:00
|
|
|
|
2007-01-29 06:10:04 +08:00
|
|
|
if field.help_text:
|
2017-03-04 22:47:49 +08:00
|
|
|
help_text = help_text_html % field.help_text
|
2007-01-29 06:10:04 +08:00
|
|
|
else:
|
2012-06-08 00:08:47 +08:00
|
|
|
help_text = ''
|
2009-12-13 02:52:12 +08:00
|
|
|
|
|
|
|
output.append(normal_row % {
|
2017-03-04 22:47:49 +08:00
|
|
|
'errors': bf_errors,
|
|
|
|
'label': label,
|
|
|
|
'field': bf,
|
2009-12-13 02:52:12 +08:00
|
|
|
'help_text': help_text,
|
2013-09-10 21:09:55 +08:00
|
|
|
'html_class_attr': html_class_attr,
|
2015-06-06 05:33:22 +08:00
|
|
|
'css_classes': css_classes,
|
2013-09-10 21:09:55 +08:00
|
|
|
'field_name': bf.html_name,
|
2009-12-13 02:52:12 +08:00
|
|
|
})
|
|
|
|
|
2006-12-07 13:35:39 +08:00
|
|
|
if top_errors:
|
2017-03-04 22:47:49 +08:00
|
|
|
output.insert(0, error_row % top_errors)
|
2009-12-13 02:52:12 +08:00
|
|
|
|
2013-11-03 03:27:47 +08:00
|
|
|
if hidden_fields: # Insert any hidden fields in the last row.
|
2012-06-08 00:08:47 +08:00
|
|
|
str_hidden = ''.join(hidden_fields)
|
2006-12-07 14:06:58 +08:00
|
|
|
if output:
|
2006-12-07 14:59:07 +08:00
|
|
|
last_row = output[-1]
|
2007-11-14 20:58:53 +08:00
|
|
|
# Chop off the trailing row_ender (e.g. '</td></tr>') and
|
|
|
|
# insert the hidden fields.
|
2008-09-18 15:16:08 +08:00
|
|
|
if not last_row.endswith(row_ender):
|
|
|
|
# This can happen in the as_p() case (and possibly others
|
|
|
|
# that users write): if there are only top errors, we may
|
|
|
|
# not be able to conscript the last row for our purposes,
|
|
|
|
# so insert a new, empty row.
|
2015-01-06 17:07:40 +08:00
|
|
|
last_row = (normal_row % {
|
|
|
|
'errors': '',
|
|
|
|
'label': '',
|
|
|
|
'field': '',
|
|
|
|
'help_text': '',
|
|
|
|
'html_class_attr': html_class_attr,
|
2015-06-06 05:33:22 +08:00
|
|
|
'css_classes': '',
|
2015-01-06 17:07:40 +08:00
|
|
|
'field_name': '',
|
|
|
|
})
|
2008-09-18 15:16:08 +08:00
|
|
|
output.append(last_row)
|
2006-12-07 14:59:07 +08:00
|
|
|
output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender
|
2007-11-14 20:58:53 +08:00
|
|
|
else:
|
|
|
|
# If there aren't any rows in the output, just append the
|
|
|
|
# hidden fields.
|
2006-12-07 14:06:58 +08:00
|
|
|
output.append(str_hidden)
|
2012-06-08 00:08:47 +08:00
|
|
|
return mark_safe('\n'.join(output))
|
2006-11-05 04:49:59 +08:00
|
|
|
|
2006-12-07 14:59:07 +08:00
|
|
|
def as_table(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"Return this form rendered as HTML <tr>s -- excluding the <table></table>."
|
2009-12-13 02:52:12 +08:00
|
|
|
return self._html_output(
|
2013-11-03 17:22:11 +08:00
|
|
|
normal_row='<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
|
|
|
|
error_row='<tr><td colspan="2">%s</td></tr>',
|
|
|
|
row_ender='</td></tr>',
|
2018-01-21 15:09:10 +08:00
|
|
|
help_text_html='<br><span class="helptext">%s</span>',
|
2018-03-16 17:54:34 +08:00
|
|
|
errors_on_separate_row=False,
|
|
|
|
)
|
2006-12-07 14:59:07 +08:00
|
|
|
|
2006-11-27 11:49:19 +08:00
|
|
|
def as_ul(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"Return this form rendered as HTML <li>s -- excluding the <ul></ul>."
|
2009-12-13 02:52:12 +08:00
|
|
|
return self._html_output(
|
2013-11-03 17:22:11 +08:00
|
|
|
normal_row='<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
|
|
|
|
error_row='<li>%s</li>',
|
|
|
|
row_ender='</li>',
|
|
|
|
help_text_html=' <span class="helptext">%s</span>',
|
2018-03-16 17:54:34 +08:00
|
|
|
errors_on_separate_row=False,
|
|
|
|
)
|
2006-12-07 14:34:37 +08:00
|
|
|
|
|
|
|
def as_p(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"Return this form rendered as HTML <p>s."
|
2009-12-13 02:52:12 +08:00
|
|
|
return self._html_output(
|
2013-11-03 17:22:11 +08:00
|
|
|
normal_row='<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
|
|
|
|
error_row='%s',
|
|
|
|
row_ender='</p>',
|
|
|
|
help_text_html=' <span class="helptext">%s</span>',
|
2018-03-16 17:54:34 +08:00
|
|
|
errors_on_separate_row=True,
|
|
|
|
)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-11-27 12:49:26 +08:00
|
|
|
def non_field_errors(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return an ErrorList of errors that aren't associated with a particular
|
|
|
|
field -- i.e., from Form.clean(). Return an empty ErrorList if there
|
2006-11-27 12:56:33 +08:00
|
|
|
are none.
|
2006-11-27 12:49:26 +08:00
|
|
|
"""
|
2014-04-15 11:58:51 +08:00
|
|
|
return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))
|
2006-11-27 12:49:26 +08:00
|
|
|
|
2013-11-12 01:56:01 +08:00
|
|
|
def add_error(self, field, error):
|
|
|
|
"""
|
|
|
|
Update the content of `self._errors`.
|
|
|
|
|
|
|
|
The `field` argument is the name of the field to which the errors
|
2017-01-25 05:23:56 +08:00
|
|
|
should be added. If it's None, treat the errors as NON_FIELD_ERRORS.
|
2013-11-12 01:56:01 +08:00
|
|
|
|
|
|
|
The `error` argument can be a single error, a list of errors, or a
|
2017-01-25 05:23:56 +08:00
|
|
|
dictionary that maps field names to lists of errors. An "error" can be
|
|
|
|
either a simple string or an instance of ValidationError with its
|
|
|
|
message attribute set and a "list or dictionary" can be an actual
|
|
|
|
`list` or `dict` or an instance of ValidationError with its
|
|
|
|
`error_list` or `error_dict` attribute set.
|
2013-11-12 01:56:01 +08:00
|
|
|
|
|
|
|
If `error` is a dictionary, the `field` argument *must* be None and
|
|
|
|
errors will be added to the fields that correspond to the keys of the
|
|
|
|
dictionary.
|
|
|
|
"""
|
|
|
|
if not isinstance(error, ValidationError):
|
|
|
|
# Normalize to ValidationError and let its constructor
|
|
|
|
# do the hard work of making sense of the input.
|
|
|
|
error = ValidationError(error)
|
|
|
|
|
|
|
|
if hasattr(error, 'error_dict'):
|
|
|
|
if field is not None:
|
|
|
|
raise TypeError(
|
|
|
|
"The argument `field` must be `None` when the `error` "
|
|
|
|
"argument contains errors for multiple fields."
|
|
|
|
)
|
|
|
|
else:
|
2013-11-30 03:38:13 +08:00
|
|
|
error = error.error_dict
|
2013-11-12 01:56:01 +08:00
|
|
|
else:
|
2013-11-30 03:38:13 +08:00
|
|
|
error = {field or NON_FIELD_ERRORS: error.error_list}
|
2013-11-12 01:56:01 +08:00
|
|
|
|
|
|
|
for field, error_list in error.items():
|
|
|
|
if field not in self.errors:
|
|
|
|
if field != NON_FIELD_ERRORS and field not in self.fields:
|
|
|
|
raise ValueError(
|
|
|
|
"'%s' has no field named '%s'." % (self.__class__.__name__, field))
|
2014-04-15 11:58:51 +08:00
|
|
|
if field == NON_FIELD_ERRORS:
|
|
|
|
self._errors[field] = self.error_class(error_class='nonfield')
|
|
|
|
else:
|
|
|
|
self._errors[field] = self.error_class()
|
2013-11-12 01:56:01 +08:00
|
|
|
self._errors[field].extend(error_list)
|
|
|
|
if field in self.cleaned_data:
|
|
|
|
del self.cleaned_data[field]
|
|
|
|
|
2014-03-23 02:08:04 +08:00
|
|
|
def has_error(self, field, code=None):
|
2017-12-27 02:44:12 +08:00
|
|
|
return field in self.errors and (
|
|
|
|
code is None or
|
|
|
|
any(error.code == code for error in self.errors.as_data()[field])
|
|
|
|
)
|
2014-03-23 02:08:04 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def full_clean(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Clean all of self.data and populate self._errors and self.cleaned_data.
|
2006-11-05 04:49:59 +08:00
|
|
|
"""
|
2007-05-26 17:02:17 +08:00
|
|
|
self._errors = ErrorDict()
|
2013-11-03 03:27:47 +08:00
|
|
|
if not self.is_bound: # Stop further processing.
|
2006-11-27 11:49:19 +08:00
|
|
|
return
|
2007-05-15 00:24:51 +08:00
|
|
|
self.cleaned_data = {}
|
2008-07-19 07:54:34 +08:00
|
|
|
# If the form is permitted to be empty, and none of the form data has
|
|
|
|
# changed from the initial data, short circuit any validation.
|
|
|
|
if self.empty_permitted and not self.has_changed():
|
|
|
|
return
|
2013-11-12 01:56:01 +08:00
|
|
|
|
2010-01-21 10:28:03 +08:00
|
|
|
self._clean_fields()
|
|
|
|
self._clean_form()
|
2010-03-07 02:42:56 +08:00
|
|
|
self._post_clean()
|
2010-01-21 10:28:03 +08:00
|
|
|
|
|
|
|
def _clean_fields(self):
|
2006-10-29 04:34:37 +08:00
|
|
|
for name, field in self.fields.items():
|
2007-08-06 21:58:56 +08:00
|
|
|
# value_from_datadict() gets the data from the data dictionaries.
|
2006-11-30 01:00:34 +08:00
|
|
|
# Each widget type knows how to retrieve its own data, because some
|
|
|
|
# widgets split data over several HTML fields.
|
2016-07-26 02:04:39 +08:00
|
|
|
if field.disabled:
|
2016-08-19 08:55:47 +08:00
|
|
|
value = self.get_initial_for_field(field, name)
|
2016-07-26 02:04:39 +08:00
|
|
|
else:
|
|
|
|
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
|
2006-10-29 04:34:37 +08:00
|
|
|
try:
|
2008-01-18 02:03:21 +08:00
|
|
|
if isinstance(field, FileField):
|
2016-08-19 08:55:47 +08:00
|
|
|
initial = self.get_initial_for_field(field, name)
|
2008-01-18 02:03:21 +08:00
|
|
|
value = field.clean(value, initial)
|
|
|
|
else:
|
|
|
|
value = field.clean(value)
|
2007-05-15 00:24:51 +08:00
|
|
|
self.cleaned_data[name] = value
|
|
|
|
if hasattr(self, 'clean_%s' % name):
|
|
|
|
value = getattr(self, 'clean_%s' % name)()
|
2007-05-26 16:47:15 +08:00
|
|
|
self.cleaned_data[name] = value
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2013-11-12 01:56:01 +08:00
|
|
|
self.add_error(name, e)
|
2010-01-21 10:28:03 +08:00
|
|
|
|
|
|
|
def _clean_form(self):
|
2006-11-05 04:49:59 +08:00
|
|
|
try:
|
2013-08-08 21:05:55 +08:00
|
|
|
cleaned_data = self.clean()
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2013-11-12 01:56:01 +08:00
|
|
|
self.add_error(None, e)
|
2013-08-08 21:05:55 +08:00
|
|
|
else:
|
|
|
|
if cleaned_data is not None:
|
|
|
|
self.cleaned_data = cleaned_data
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2010-03-07 02:42:56 +08:00
|
|
|
def _post_clean(self):
|
|
|
|
"""
|
|
|
|
An internal hook for performing additional cleaning after form cleaning
|
|
|
|
is complete. Used for model validation in model forms.
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(self):
|
|
|
|
"""
|
2014-08-02 21:14:13 +08:00
|
|
|
Hook for doing any extra form-wide cleaning after Field.clean() has been
|
2006-11-27 12:49:26 +08:00
|
|
|
called on every field. Any ValidationError raised by this method will
|
|
|
|
not be associated with a particular field; it will have a special-case
|
|
|
|
association with the field named '__all__'.
|
2006-11-05 04:49:59 +08:00
|
|
|
"""
|
2013-08-08 21:27:48 +08:00
|
|
|
return self.cleaned_data
|
2006-11-05 04:49:59 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def has_changed(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return True if data differs from initial."""
|
2008-07-19 07:54:34 +08:00
|
|
|
return bool(self.changed_data)
|
2008-09-02 05:28:32 +08:00
|
|
|
|
2015-08-04 08:14:15 +08:00
|
|
|
@cached_property
|
2013-01-26 05:41:45 +08:00
|
|
|
def changed_data(self):
|
2015-08-04 08:14:15 +08:00
|
|
|
data = []
|
|
|
|
for name, field in self.fields.items():
|
|
|
|
prefixed_name = self.add_prefix(name)
|
|
|
|
data_value = field.widget.value_from_datadict(self.data, self.files, prefixed_name)
|
|
|
|
if not field.show_hidden_initial:
|
2016-08-19 08:55:47 +08:00
|
|
|
# Use the BoundField's initial as this is the value passed to
|
|
|
|
# the widget.
|
|
|
|
initial_value = self[name].initial
|
2015-08-04 08:14:15 +08:00
|
|
|
else:
|
|
|
|
initial_prefixed_name = self.add_initial_prefix(name)
|
|
|
|
hidden_widget = field.hidden_widget()
|
|
|
|
try:
|
|
|
|
initial_value = field.to_python(hidden_widget.value_from_datadict(
|
|
|
|
self.data, self.files, initial_prefixed_name))
|
|
|
|
except ValidationError:
|
|
|
|
# Always assume data has changed if validation fails.
|
|
|
|
data.append(name)
|
|
|
|
continue
|
|
|
|
if field.has_changed(initial_value, data_value):
|
|
|
|
data.append(name)
|
|
|
|
return data
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2013-01-26 05:41:45 +08:00
|
|
|
@property
|
|
|
|
def media(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return all media required to render the widgets on this form."""
|
2008-07-19 07:54:34 +08:00
|
|
|
media = Media()
|
|
|
|
for field in self.fields.values():
|
|
|
|
media = media + field.widget.media
|
|
|
|
return media
|
|
|
|
|
2007-09-15 18:12:05 +08:00
|
|
|
def is_multipart(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return True if the form needs to be multipart-encoded, i.e. it has
|
|
|
|
FileInput, or False otherwise.
|
2007-09-15 18:12:05 +08:00
|
|
|
"""
|
2017-12-27 02:44:12 +08:00
|
|
|
return any(field.widget.needs_multipart_form for field in self.fields.values())
|
2007-09-15 18:12:05 +08:00
|
|
|
|
2008-12-05 12:22:00 +08:00
|
|
|
def hidden_fields(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return a list of all the BoundField objects that are hidden fields.
|
2008-12-08 12:07:42 +08:00
|
|
|
Useful for manual form layout in templates.
|
2008-12-05 12:22:00 +08:00
|
|
|
"""
|
|
|
|
return [field for field in self if field.is_hidden]
|
|
|
|
|
|
|
|
def visible_fields(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return a list of BoundField objects that aren't hidden fields.
|
2008-12-08 12:07:42 +08:00
|
|
|
The opposite of the hidden_fields() method.
|
2008-12-05 12:22:00 +08:00
|
|
|
"""
|
|
|
|
return [field for field in self if not field.is_hidden]
|
|
|
|
|
2016-08-19 08:55:47 +08:00
|
|
|
def get_initial_for_field(self, field, field_name):
|
|
|
|
"""
|
|
|
|
Return initial data for field on form. Use initial data from the form
|
|
|
|
or the field, in that order. Evaluate callable values.
|
|
|
|
"""
|
|
|
|
value = self.initial.get(field_name, field.initial)
|
|
|
|
if callable(value):
|
|
|
|
value = value()
|
|
|
|
return value
|
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2017-01-07 19:11:46 +08:00
|
|
|
class Form(BaseForm, metaclass=DeclarativeFieldsMetaclass):
|
2006-12-15 13:35:19 +08:00
|
|
|
"A collection of Fields, plus their associated data."
|
|
|
|
# This is a separate class from BaseForm in order to abstract the way
|
|
|
|
# self.fields is specified. This class (Form) is the one that does the
|
|
|
|
# fancy metaclass stuff purely for the semantic sugar -- it allows one
|
|
|
|
# to define a form using declarative syntax.
|
|
|
|
# BaseForm itself has no way of designating self.fields.
|