2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Form classes
|
|
|
|
"""
|
|
|
|
|
2013-07-30 01:19:04 +08:00
|
|
|
from __future__ import unicode_literals
|
2011-10-18 00:39:53 +08:00
|
|
|
|
2013-08-03 13:41:15 +08:00
|
|
|
from collections import OrderedDict
|
2011-03-28 10:11:19 +08:00
|
|
|
import copy
|
2013-02-25 05:58:07 +08:00
|
|
|
import warnings
|
2011-10-18 00:39:53 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
from django.core.exceptions import ValidationError
|
2011-10-18 00:39:53 +08:00
|
|
|
from django.forms.fields import Field, FileField
|
2013-09-17 00:52:05 +08:00
|
|
|
from django.forms.utils import flatatt, ErrorDict, ErrorList
|
2011-10-18 00:39:53 +08:00
|
|
|
from django.forms.widgets import Media, media_property, TextInput, Textarea
|
2012-07-03 07:31:14 +08:00
|
|
|
from django.utils.html import conditional_escape, format_html
|
2012-08-12 18:32:08 +08:00
|
|
|
from django.utils.encoding import smart_text, force_text, python_2_unicode_compatible
|
2007-11-14 20:58:53 +08:00
|
|
|
from django.utils.safestring import mark_safe
|
2013-01-27 02:57:10 +08:00
|
|
|
from django.utils.translation import ugettext as _
|
2012-07-21 03:20:42 +08:00
|
|
|
from django.utils import six
|
2007-05-17 05:20:35 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-12-17 13:11:48 +08:00
|
|
|
__all__ = ('BaseForm', 'Form')
|
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
NON_FIELD_ERRORS = '__all__'
|
|
|
|
|
|
|
|
def pretty_name(name):
|
2010-08-14 20:05:41 +08:00
|
|
|
"""Converts 'first_name' to 'First name'"""
|
|
|
|
if not name:
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''
|
2010-08-14 20:05:41 +08:00
|
|
|
return name.replace('_', ' ').capitalize()
|
2006-11-05 04:49:59 +08:00
|
|
|
|
2008-02-15 01:38:05 +08:00
|
|
|
def get_declared_fields(bases, attrs, with_base_fields=True):
|
|
|
|
"""
|
|
|
|
Create a list of form field instances from the passed in 'attrs', plus any
|
|
|
|
similar fields on the base classes (in 'bases'). This is used by both the
|
2013-01-31 02:48:05 +08:00
|
|
|
Form and ModelForm metaclasses.
|
2008-02-15 01:38:05 +08:00
|
|
|
|
|
|
|
If 'with_base_fields' is True, all fields from the bases are used.
|
|
|
|
Otherwise, only fields in the 'declared_fields' attribute on the bases are
|
|
|
|
used. The distinction is useful in ModelForm subclassing.
|
2013-01-31 02:48:05 +08:00
|
|
|
Also integrates any additional media definitions.
|
2008-02-15 01:38:05 +08:00
|
|
|
"""
|
2012-07-21 03:14:27 +08:00
|
|
|
fields = [(field_name, attrs.pop(field_name)) for field_name, obj in list(six.iteritems(attrs)) if isinstance(obj, Field)]
|
2010-08-07 00:31:44 +08:00
|
|
|
fields.sort(key=lambda x: x[1].creation_counter)
|
2008-02-14 20:56:49 +08:00
|
|
|
|
|
|
|
# If this class is subclassing another Form, add that Form's fields.
|
|
|
|
# Note that we loop over the bases in *reverse*. This is necessary in
|
|
|
|
# order to preserve the correct order of fields.
|
2008-02-15 01:38:05 +08:00
|
|
|
if with_base_fields:
|
|
|
|
for base in bases[::-1]:
|
|
|
|
if hasattr(base, 'base_fields'):
|
2012-07-21 03:14:27 +08:00
|
|
|
fields = list(six.iteritems(base.base_fields)) + fields
|
2008-02-15 01:38:05 +08:00
|
|
|
else:
|
|
|
|
for base in bases[::-1]:
|
|
|
|
if hasattr(base, 'declared_fields'):
|
2012-07-21 03:14:27 +08:00
|
|
|
fields = list(six.iteritems(base.declared_fields)) + fields
|
2008-02-14 20:56:49 +08:00
|
|
|
|
2013-08-03 13:41:15 +08:00
|
|
|
return OrderedDict(fields)
|
2008-02-14 20:56:49 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class DeclarativeFieldsMetaclass(type):
|
2007-02-15 07:44:46 +08:00
|
|
|
"""
|
|
|
|
Metaclass that converts Field attributes to a dictionary called
|
|
|
|
'base_fields', taking into account parent class 'base_fields' as well.
|
|
|
|
"""
|
2006-10-29 04:34:37 +08:00
|
|
|
def __new__(cls, name, bases, attrs):
|
2008-02-14 20:56:49 +08:00
|
|
|
attrs['base_fields'] = get_declared_fields(bases, attrs)
|
2008-07-19 07:54:34 +08:00
|
|
|
new_class = super(DeclarativeFieldsMetaclass,
|
2008-07-06 19:55:30 +08:00
|
|
|
cls).__new__(cls, name, bases, attrs)
|
2008-07-19 07:54:34 +08:00
|
|
|
if 'media' not in attrs:
|
|
|
|
new_class.media = media_property(new_class)
|
|
|
|
return new_class
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
@python_2_unicode_compatible
|
|
|
|
class BaseForm(object):
|
2006-12-15 13:35:19 +08:00
|
|
|
# This is 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
|
|
|
|
# information. Any improvements to the form API should be made to *this*
|
|
|
|
# class, not to the Form class.
|
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,
|
2008-07-19 07:54:34 +08:00
|
|
|
empty_permitted=False):
|
2007-08-06 21:58:56 +08:00
|
|
|
self.is_bound = data is not None or files is not None
|
2006-10-29 04:34:37 +08:00
|
|
|
self.data = data or {}
|
2007-08-06 21:58:56 +08:00
|
|
|
self.files = files or {}
|
2006-11-16 07:09:10 +08:00
|
|
|
self.auto_id = auto_id
|
2006-12-12 13:55:39 +08:00
|
|
|
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
|
2007-05-26 16:53:22 +08:00
|
|
|
self._errors = None # Stores the errors after clean() has been called.
|
2008-07-19 07:54:34 +08:00
|
|
|
self._changed_data = None
|
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)
|
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
|
|
|
|
|
|
|
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):
|
|
|
|
"Returns a BoundField with the given name."
|
|
|
|
try:
|
|
|
|
field = self.fields[name]
|
|
|
|
except KeyError:
|
|
|
|
raise KeyError('Key %r not found in Form' % name)
|
|
|
|
return BoundField(self, field, name)
|
|
|
|
|
2013-01-26 05:41:45 +08:00
|
|
|
@property
|
|
|
|
def errors(self):
|
2007-08-06 21:58:56 +08:00
|
|
|
"Returns 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):
|
|
|
|
"""
|
2006-11-27 11:49:19 +08:00
|
|
|
Returns True if the form has no errors. Otherwise, False. If errors are
|
|
|
|
being ignored, returns False.
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
2007-01-05 08:04:38 +08:00
|
|
|
return self.is_bound and not bool(self.errors)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-12-12 13:55:39 +08:00
|
|
|
def add_prefix(self, field_name):
|
|
|
|
"""
|
|
|
|
Returns the field name with a prefix appended, if this Form has a
|
|
|
|
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):
|
|
|
|
"""
|
|
|
|
Add a '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):
|
2006-12-07 14:59:07 +08:00
|
|
|
"Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
|
|
|
|
top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
|
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]
|
2013-01-27 02:57:10 +08:00
|
|
|
# Escape and cache in local variable.
|
|
|
|
bf_errors = self.error_class([conditional_escape(error) for error in 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(
|
|
|
|
[_('(Hidden field %(name)s) %(error)s') % {'name': name, 'error': force_text(e)}
|
|
|
|
for e in bf_errors])
|
2012-07-20 20:48:51 +08:00
|
|
|
hidden_fields.append(six.text_type(bf))
|
2006-12-01 01:07:40 +08:00
|
|
|
else:
|
2009-12-13 02:52:12 +08:00
|
|
|
# Create a 'class="..."' atribute if the row should have any
|
|
|
|
# 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:
|
2012-07-21 16:00:10 +08:00
|
|
|
output.append(error_row % force_text(bf_errors))
|
2009-12-13 02:52:12 +08:00
|
|
|
|
2007-04-27 22:27:07 +08:00
|
|
|
if bf.label:
|
2012-07-21 16:00:10 +08:00
|
|
|
label = conditional_escape(force_text(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:
|
2012-07-21 16:00:10 +08:00
|
|
|
help_text = help_text_html % force_text(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 % {
|
2012-07-21 16:00:10 +08:00
|
|
|
'errors': force_text(bf_errors),
|
|
|
|
'label': force_text(label),
|
2012-07-20 20:48:51 +08:00
|
|
|
'field': six.text_type(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,
|
|
|
|
'field_name': bf.html_name,
|
2009-12-13 02:52:12 +08:00
|
|
|
})
|
|
|
|
|
2006-12-07 13:35:39 +08:00
|
|
|
if top_errors:
|
2012-07-21 16:00:10 +08:00
|
|
|
output.insert(0, error_row % force_text(top_errors))
|
2009-12-13 02:52:12 +08:00
|
|
|
|
2006-12-07 14:59:07 +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.
|
2009-12-13 02:52:12 +08:00
|
|
|
last_row = (normal_row % {'errors': '', 'label': '',
|
|
|
|
'field': '', 'help_text':'',
|
|
|
|
'html_class_attr': html_class_attr})
|
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):
|
|
|
|
"Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
|
2009-12-13 02:52:12 +08:00
|
|
|
return self._html_output(
|
2012-06-08 00:08:47 +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>',
|
|
|
|
help_text_html = '<br /><span class="helptext">%s</span>',
|
2009-12-13 02:52:12 +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):
|
|
|
|
"Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
|
2009-12-13 02:52:12 +08:00
|
|
|
return self._html_output(
|
2012-06-08 00:08:47 +08:00
|
|
|
normal_row = '<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
|
|
|
|
error_row = '<li>%s</li>',
|
2009-12-13 02:52:12 +08:00
|
|
|
row_ender = '</li>',
|
2012-06-08 00:08:47 +08:00
|
|
|
help_text_html = ' <span class="helptext">%s</span>',
|
2009-12-13 02:52:12 +08:00
|
|
|
errors_on_separate_row = False)
|
2006-12-07 14:34:37 +08:00
|
|
|
|
|
|
|
def as_p(self):
|
|
|
|
"Returns this form rendered as HTML <p>s."
|
2009-12-13 02:52:12 +08:00
|
|
|
return self._html_output(
|
2012-06-08 00:08:47 +08:00
|
|
|
normal_row = '<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
|
|
|
|
error_row = '%s',
|
2009-12-13 02:52:12 +08:00
|
|
|
row_ender = '</p>',
|
2012-06-08 00:08:47 +08:00
|
|
|
help_text_html = ' <span class="helptext">%s</span>',
|
2009-12-13 02:52:12 +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):
|
|
|
|
"""
|
2006-11-27 12:56:33 +08:00
|
|
|
Returns an ErrorList of errors that aren't associated with a particular
|
|
|
|
field -- i.e., from Form.clean(). Returns an empty ErrorList if there
|
|
|
|
are none.
|
2006-11-27 12:49:26 +08:00
|
|
|
"""
|
2007-09-14 07:09:40 +08:00
|
|
|
return self.errors.get(NON_FIELD_ERRORS, self.error_class())
|
2006-11-27 12:49:26 +08:00
|
|
|
|
2009-04-01 03:55:20 +08:00
|
|
|
def _raw_value(self, fieldname):
|
|
|
|
"""
|
|
|
|
Returns the raw_value for a particular field name. This is just a
|
|
|
|
convenient wrapper around widget.value_from_datadict.
|
|
|
|
"""
|
|
|
|
field = self.fields[fieldname]
|
|
|
|
prefix = self.add_prefix(fieldname)
|
|
|
|
return field.widget.value_from_datadict(self.data, self.files, prefix)
|
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def full_clean(self):
|
|
|
|
"""
|
2007-05-26 16:53:22 +08:00
|
|
|
Cleans all of self.data and populates 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()
|
2007-01-05 08:04:38 +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
|
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.
|
2007-08-06 21:58:56 +08:00
|
|
|
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):
|
|
|
|
initial = self.initial.get(name, field.initial)
|
|
|
|
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:
|
2009-09-11 18:47:40 +08:00
|
|
|
self._errors[name] = self.error_class(e.messages)
|
2007-05-26 16:47:15 +08:00
|
|
|
if name in self.cleaned_data:
|
|
|
|
del self.cleaned_data[name]
|
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:
|
2009-09-11 18:47:40 +08:00
|
|
|
self._errors[NON_FIELD_ERRORS] = self.error_class(e.messages)
|
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):
|
|
|
|
"""
|
|
|
|
Hook for doing any extra form-wide cleaning after Field.clean() 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):
|
|
|
|
"""
|
|
|
|
Returns True if data differs from initial.
|
|
|
|
"""
|
|
|
|
return bool(self.changed_data)
|
2008-09-02 05:28:32 +08:00
|
|
|
|
2013-01-26 05:41:45 +08:00
|
|
|
@property
|
|
|
|
def changed_data(self):
|
2008-07-19 07:54:34 +08:00
|
|
|
if self._changed_data is None:
|
|
|
|
self._changed_data = []
|
|
|
|
# XXX: For now we're asking the individual widgets whether or not the
|
|
|
|
# data has changed. It would probably be more efficient to hash the
|
|
|
|
# initial data, store it in a hidden field, and compare a hash of the
|
|
|
|
# submitted data, but we'd need a way to easily get the string value
|
|
|
|
# for a given field. Right now, that logic is embedded in the render
|
|
|
|
# method of each widget.
|
|
|
|
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)
|
2008-09-02 05:28:32 +08:00
|
|
|
if not field.show_hidden_initial:
|
|
|
|
initial_value = self.initial.get(name, field.initial)
|
2012-08-04 00:17:41 +08:00
|
|
|
if callable(initial_value):
|
|
|
|
initial_value = initial_value()
|
2008-09-02 05:28:32 +08:00
|
|
|
else:
|
|
|
|
initial_prefixed_name = self.add_initial_prefix(name)
|
|
|
|
hidden_widget = field.hidden_widget()
|
2013-03-09 01:16:38 +08:00
|
|
|
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.
|
|
|
|
self._changed_data.append(name)
|
|
|
|
continue
|
2013-01-26 03:50:46 +08:00
|
|
|
if hasattr(field.widget, '_has_changed'):
|
|
|
|
warnings.warn("The _has_changed method on widgets is deprecated,"
|
|
|
|
" define it at field level instead.",
|
2013-06-30 00:34:41 +08:00
|
|
|
DeprecationWarning, stacklevel=2)
|
2013-01-26 03:50:46 +08:00
|
|
|
if field.widget._has_changed(initial_value, data_value):
|
|
|
|
self._changed_data.append(name)
|
|
|
|
elif field._has_changed(initial_value, data_value):
|
2008-07-19 07:54:34 +08:00
|
|
|
self._changed_data.append(name)
|
|
|
|
return self._changed_data
|
|
|
|
|
2013-01-26 05:41:45 +08:00
|
|
|
@property
|
|
|
|
def media(self):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
Provide a description of all media required to render the widgets on this form
|
|
|
|
"""
|
|
|
|
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):
|
|
|
|
"""
|
2011-10-19 04:28:52 +08:00
|
|
|
Returns True if the form needs to be multipart-encoded, i.e. it has
|
2007-09-15 18:12:05 +08:00
|
|
|
FileInput. Otherwise, False.
|
|
|
|
"""
|
|
|
|
for field in self.fields.values():
|
|
|
|
if field.widget.needs_multipart_form:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2008-12-05 12:22:00 +08:00
|
|
|
def hidden_fields(self):
|
|
|
|
"""
|
2008-12-08 12:07:42 +08:00
|
|
|
Returns a list of all the BoundField objects that are hidden fields.
|
|
|
|
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):
|
|
|
|
"""
|
2008-12-08 12:07:42 +08:00
|
|
|
Returns a list of BoundField objects that aren't hidden fields.
|
|
|
|
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]
|
|
|
|
|
2012-07-21 03:20:42 +08:00
|
|
|
class Form(six.with_metaclass(DeclarativeFieldsMetaclass, BaseForm)):
|
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.
|
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
@python_2_unicode_compatible
|
|
|
|
class BoundField(object):
|
2006-10-29 04:34:37 +08:00
|
|
|
"A Field plus data"
|
|
|
|
def __init__(self, form, field, name):
|
2006-12-06 02:48:49 +08:00
|
|
|
self.form = form
|
|
|
|
self.field = field
|
2006-12-14 07:03:19 +08:00
|
|
|
self.name = name
|
|
|
|
self.html_name = form.add_prefix(name)
|
2008-09-02 05:28:32 +08:00
|
|
|
self.html_initial_name = form.add_initial_prefix(name)
|
2009-12-13 02:18:31 +08:00
|
|
|
self.html_initial_id = form.add_initial_prefix(self.auto_id)
|
2006-12-27 07:33:20 +08:00
|
|
|
if self.field.label is None:
|
|
|
|
self.label = pretty_name(name)
|
|
|
|
else:
|
|
|
|
self.label = self.field.label
|
2007-02-16 06:43:43 +08:00
|
|
|
self.help_text = field.help_text or ''
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
def __str__(self):
|
2007-08-01 13:41:32 +08:00
|
|
|
"""Renders this field as an HTML widget."""
|
2008-09-02 05:28:32 +08:00
|
|
|
if self.field.show_hidden_initial:
|
|
|
|
return self.as_widget() + self.as_hidden(only_initial=True)
|
2007-08-01 13:41:32 +08:00
|
|
|
return self.as_widget()
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2011-12-08 06:31:39 +08:00
|
|
|
def __iter__(self):
|
|
|
|
"""
|
|
|
|
Yields rendered strings that comprise all widgets in this BoundField.
|
|
|
|
|
|
|
|
This really is only useful for RadioSelect widgets, so that you can
|
|
|
|
iterate over individual radio buttons in a template.
|
|
|
|
"""
|
2013-06-05 04:41:49 +08:00
|
|
|
id_ = self.field.widget.attrs.get('id') or self.auto_id
|
|
|
|
attrs = {'id': id_} if id_ else {}
|
|
|
|
for subwidget in self.field.widget.subwidgets(self.html_name, self.value(), attrs):
|
2011-12-08 07:08:27 +08:00
|
|
|
yield subwidget
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(list(self.__iter__()))
|
|
|
|
|
|
|
|
def __getitem__(self, idx):
|
|
|
|
return list(self.__iter__())[idx]
|
2011-12-08 06:31:39 +08:00
|
|
|
|
2013-01-26 05:41:45 +08:00
|
|
|
@property
|
|
|
|
def errors(self):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Returns an ErrorList for this field. Returns an empty ErrorList
|
|
|
|
if there are none.
|
|
|
|
"""
|
2007-09-14 07:09:40 +08:00
|
|
|
return self.form.errors.get(self.name, self.form.error_class())
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2008-09-02 05:28:32 +08:00
|
|
|
def as_widget(self, widget=None, attrs=None, only_initial=False):
|
2007-08-01 13:41:32 +08:00
|
|
|
"""
|
|
|
|
Renders the field by rendering the passed widget, adding any HTML
|
|
|
|
attributes passed as attrs. If no widget is specified, then the
|
|
|
|
field's default widget will be used.
|
|
|
|
"""
|
|
|
|
if not widget:
|
|
|
|
widget = self.field.widget
|
2010-08-14 20:05:41 +08:00
|
|
|
|
2013-09-22 04:54:00 +08:00
|
|
|
if self.field.localize:
|
|
|
|
widget.is_localized = True
|
|
|
|
|
2006-11-16 07:09:10 +08:00
|
|
|
attrs = attrs or {}
|
|
|
|
auto_id = self.auto_id
|
2007-04-26 21:30:48 +08:00
|
|
|
if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
|
2009-12-13 02:18:31 +08:00
|
|
|
if not only_initial:
|
|
|
|
attrs['id'] = auto_id
|
|
|
|
else:
|
|
|
|
attrs['id'] = self.html_initial_id
|
2010-08-14 20:05:41 +08:00
|
|
|
|
2008-09-02 05:28:32 +08:00
|
|
|
if not only_initial:
|
|
|
|
name = self.html_name
|
|
|
|
else:
|
|
|
|
name = self.html_initial_name
|
2010-11-28 10:50:31 +08:00
|
|
|
return widget.render(name, self.value(), attrs=attrs)
|
2008-12-05 12:22:00 +08:00
|
|
|
|
2008-09-02 05:28:32 +08:00
|
|
|
def as_text(self, attrs=None, **kwargs):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Returns a string of HTML for representing this as an <input type="text">.
|
|
|
|
"""
|
2008-09-02 05:28:32 +08:00
|
|
|
return self.as_widget(TextInput(), attrs, **kwargs)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2008-09-02 05:28:32 +08:00
|
|
|
def as_textarea(self, attrs=None, **kwargs):
|
2006-10-29 04:34:37 +08:00
|
|
|
"Returns a string of HTML for representing this as a <textarea>."
|
2008-09-02 05:28:32 +08:00
|
|
|
return self.as_widget(Textarea(), attrs, **kwargs)
|
2006-11-16 07:09:10 +08:00
|
|
|
|
2008-09-02 05:28:32 +08:00
|
|
|
def as_hidden(self, attrs=None, **kwargs):
|
2006-11-30 11:58:25 +08:00
|
|
|
"""
|
|
|
|
Returns a string of HTML for representing this as an <input type="hidden">.
|
|
|
|
"""
|
2008-09-02 05:28:32 +08:00
|
|
|
return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
|
2006-11-30 11:58:25 +08:00
|
|
|
|
2013-01-26 05:41:45 +08:00
|
|
|
@property
|
|
|
|
def data(self):
|
2006-12-28 08:01:52 +08:00
|
|
|
"""
|
|
|
|
Returns the data for this BoundField, or None if it wasn't given.
|
|
|
|
"""
|
2007-08-06 21:58:56 +08:00
|
|
|
return self.field.widget.value_from_datadict(self.form.data, self.form.files, self.html_name)
|
2006-11-30 05:48:58 +08:00
|
|
|
|
2010-11-28 10:50:31 +08:00
|
|
|
def value(self):
|
|
|
|
"""
|
|
|
|
Returns the value for this BoundField, using the initial value if
|
|
|
|
the form is not bound or the data otherwise.
|
|
|
|
"""
|
|
|
|
if not self.form.is_bound:
|
|
|
|
data = self.form.initial.get(self.name, self.field.initial)
|
|
|
|
if callable(data):
|
|
|
|
data = data()
|
|
|
|
else:
|
|
|
|
data = self.field.bound_data(
|
|
|
|
self.data, self.form.initial.get(self.name, self.field.initial)
|
|
|
|
)
|
|
|
|
return self.field.prepare_value(data)
|
|
|
|
|
2013-07-27 02:43:46 +08:00
|
|
|
def label_tag(self, contents=None, attrs=None, label_suffix=None):
|
2006-11-29 08:49:27 +08:00
|
|
|
"""
|
|
|
|
Wraps the given contents in a <label>, if the field has an ID attribute.
|
2012-07-03 07:31:14 +08:00
|
|
|
contents should be 'mark_safe'd to avoid HTML escaping. If contents
|
|
|
|
aren't given, uses the field's HTML-escaped label.
|
2007-01-21 04:31:17 +08:00
|
|
|
|
|
|
|
If attrs are given, they're used as HTML attributes on the <label> tag.
|
2013-07-27 02:43:46 +08:00
|
|
|
|
|
|
|
label_suffix allows overriding the form's label_suffix.
|
2006-11-29 08:49:27 +08:00
|
|
|
"""
|
2013-04-06 22:04:30 +08:00
|
|
|
contents = contents or self.label
|
2012-06-08 21:32:35 +08:00
|
|
|
# Only add the suffix if the label does not end in punctuation.
|
2013-08-22 15:14:06 +08:00
|
|
|
label_suffix = label_suffix if label_suffix is not None else self.form.label_suffix
|
2013-07-13 17:43:14 +08:00
|
|
|
# Translators: If found as last label character, these punctuation
|
|
|
|
# characters will prevent the default label_suffix to be appended to the label
|
2013-07-27 02:43:46 +08:00
|
|
|
if label_suffix and contents and contents[-1] not in _(':?.!'):
|
|
|
|
contents = format_html('{0}{1}', contents, label_suffix)
|
2006-12-06 02:48:49 +08:00
|
|
|
widget = self.field.widget
|
2006-11-29 09:40:27 +08:00
|
|
|
id_ = widget.attrs.get('id') or self.auto_id
|
2006-11-29 08:49:27 +08:00
|
|
|
if id_:
|
2013-05-25 21:18:48 +08:00
|
|
|
id_for_label = widget.id_for_label(id_)
|
|
|
|
if id_for_label:
|
|
|
|
attrs = dict(attrs or {}, **{'for': id_for_label})
|
2013-05-17 22:33:36 +08:00
|
|
|
attrs = flatatt(attrs) if attrs else ''
|
2013-05-25 21:18:48 +08:00
|
|
|
contents = format_html('<label{0}>{1}</label>', attrs, contents)
|
2013-04-06 22:04:30 +08:00
|
|
|
else:
|
|
|
|
contents = conditional_escape(contents)
|
2007-11-14 20:58:53 +08:00
|
|
|
return mark_safe(contents)
|
2006-11-27 12:23:20 +08:00
|
|
|
|
2009-12-13 02:52:12 +08:00
|
|
|
def css_classes(self, extra_classes=None):
|
|
|
|
"""
|
|
|
|
Returns a string of space-separated CSS classes for this field.
|
|
|
|
"""
|
|
|
|
if hasattr(extra_classes, 'split'):
|
|
|
|
extra_classes = extra_classes.split()
|
|
|
|
extra_classes = set(extra_classes or [])
|
|
|
|
if self.errors and hasattr(self.form, 'error_css_class'):
|
|
|
|
extra_classes.add(self.form.error_css_class)
|
|
|
|
if self.field.required and hasattr(self.form, 'required_css_class'):
|
|
|
|
extra_classes.add(self.form.required_css_class)
|
|
|
|
return ' '.join(extra_classes)
|
|
|
|
|
2013-01-26 05:41:45 +08:00
|
|
|
@property
|
|
|
|
def is_hidden(self):
|
2006-12-01 01:07:40 +08:00
|
|
|
"Returns True if this BoundField's widget is hidden."
|
2006-12-06 02:48:49 +08:00
|
|
|
return self.field.widget.is_hidden
|
2006-12-01 01:07:40 +08:00
|
|
|
|
2013-01-26 05:41:45 +08:00
|
|
|
@property
|
|
|
|
def auto_id(self):
|
2006-11-16 07:09:10 +08:00
|
|
|
"""
|
|
|
|
Calculates and returns the ID attribute for this BoundField, if the
|
|
|
|
associated Form has specified auto_id. Returns an empty string otherwise.
|
|
|
|
"""
|
2006-12-06 02:48:49 +08:00
|
|
|
auto_id = self.form.auto_id
|
2012-07-21 16:00:10 +08:00
|
|
|
if auto_id and '%s' in smart_text(auto_id):
|
|
|
|
return smart_text(auto_id) % self.html_name
|
2006-11-16 07:09:10 +08:00
|
|
|
elif auto_id:
|
2006-12-14 07:03:19 +08:00
|
|
|
return self.html_name
|
2006-11-16 07:09:10 +08:00
|
|
|
return ''
|
2011-02-08 20:00:21 +08:00
|
|
|
|
2013-01-26 05:41:45 +08:00
|
|
|
@property
|
|
|
|
def id_for_label(self):
|
2011-02-08 20:00:21 +08:00
|
|
|
"""
|
2012-02-05 16:12:07 +08:00
|
|
|
Wrapper around the field widget's `id_for_label` method.
|
2011-02-08 20:00:21 +08:00
|
|
|
Useful, for example, for focusing on this field regardless of whether
|
|
|
|
it has a single widget or a MutiWidget.
|
|
|
|
"""
|
|
|
|
widget = self.field.widget
|
|
|
|
id_ = widget.attrs.get('id') or self.auto_id
|
|
|
|
return widget.id_for_label(id_)
|