2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Form classes
|
|
|
|
"""
|
|
|
|
|
2006-12-13 14:26:04 +08:00
|
|
|
from django.utils.datastructures import SortedDict, MultiValueDict
|
2006-11-29 08:49:27 +08:00
|
|
|
from django.utils.html import escape
|
2007-04-04 14:34:19 +08:00
|
|
|
from django.utils.encoding import StrAndUnicode
|
2006-10-29 04:34:37 +08:00
|
|
|
from fields import Field
|
2007-01-21 04:33:23 +08:00
|
|
|
from widgets import TextInput, Textarea, HiddenInput, MultipleHiddenInput
|
2007-04-04 14:34:19 +08:00
|
|
|
from util import flatatt, ErrorDict, ErrorList, ValidationError
|
2007-02-14 02:04:47 +08:00
|
|
|
import copy
|
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):
|
|
|
|
"Converts 'first_name' to 'First name'"
|
|
|
|
name = name[0].upper() + name[1:]
|
|
|
|
return name.replace('_', ' ')
|
|
|
|
|
2006-11-24 01:40:33 +08:00
|
|
|
class SortedDictFromList(SortedDict):
|
|
|
|
"A dictionary that keeps its keys in the order in which they're inserted."
|
|
|
|
# This is different than django.utils.datastructures.SortedDict, because
|
|
|
|
# this takes a list/tuple as the argument to __init__().
|
|
|
|
def __init__(self, data=None):
|
|
|
|
if data is None: data = []
|
|
|
|
self.keyOrder = [d[0] for d in data]
|
|
|
|
dict.__init__(self, dict(data))
|
|
|
|
|
2007-01-28 06:06:56 +08:00
|
|
|
def copy(self):
|
2007-02-14 02:04:47 +08:00
|
|
|
return SortedDictFromList([(k, copy.copy(v)) for k, v in self.items()])
|
2007-01-28 06:06:56 +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):
|
2007-01-11 06:46:06 +08:00
|
|
|
fields = [(field_name, attrs.pop(field_name)) for field_name, obj in attrs.items() if isinstance(obj, Field)]
|
2006-11-24 01:40:33 +08:00
|
|
|
fields.sort(lambda x, y: cmp(x[1].creation_counter, y[1].creation_counter))
|
2007-02-15 07:44:46 +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.
|
|
|
|
for base in bases[::-1]:
|
|
|
|
if hasattr(base, 'base_fields'):
|
|
|
|
fields = base.base_fields.items() + fields
|
|
|
|
|
2007-01-28 06:06:56 +08:00
|
|
|
attrs['base_fields'] = SortedDictFromList(fields)
|
2006-10-29 04:34:37 +08:00
|
|
|
return type.__new__(cls, name, bases, attrs)
|
|
|
|
|
2006-12-15 13:35:19 +08:00
|
|
|
class BaseForm(StrAndUnicode):
|
|
|
|
# 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-01-09 12:39:44 +08:00
|
|
|
def __init__(self, data=None, auto_id='id_%s', prefix=None, initial=None):
|
2007-01-05 08:04:38 +08:00
|
|
|
self.is_bound = data is not None
|
2006-10-29 04:34:37 +08:00
|
|
|
self.data = data 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 {}
|
2006-11-05 04:49:59 +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.
|
|
|
|
self.fields = self.base_fields.copy()
|
2006-11-05 04:49:59 +08:00
|
|
|
|
2006-12-06 04:08:27 +08:00
|
|
|
def __unicode__(self):
|
2006-11-05 04:49:59 +08:00
|
|
|
return self.as_table()
|
2006-10-29 04:34:37 +08:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
for name, field in self.fields.items():
|
|
|
|
yield BoundField(self, field, name)
|
|
|
|
|
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)
|
|
|
|
|
2006-11-27 09:55:24 +08:00
|
|
|
def _errors(self):
|
2006-10-29 04:34:37 +08:00
|
|
|
"Returns an ErrorDict for self.data"
|
|
|
|
if self.__errors is None:
|
2006-11-05 04:49:59 +08:00
|
|
|
self.full_clean()
|
2006-10-29 04:34:37 +08:00
|
|
|
return self.__errors
|
2006-11-27 09:55:24 +08:00
|
|
|
errors = property(_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.
|
|
|
|
"""
|
|
|
|
return self.prefix and ('%s-%s' % (self.prefix, field_name)) or field_name
|
|
|
|
|
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 = [], []
|
2006-11-05 04:49:59 +08:00
|
|
|
for name, field in self.fields.items():
|
|
|
|
bf = BoundField(self, field, name)
|
2007-02-20 07:54:55 +08:00
|
|
|
bf_errors = ErrorList([escape(error) for error in bf.errors]) # Escape and cache in local variable.
|
2006-12-01 01:07:40 +08:00
|
|
|
if bf.is_hidden:
|
2006-12-07 13:35:39 +08:00
|
|
|
if bf_errors:
|
|
|
|
top_errors.extend(['(Hidden field %s) %s' % (name, e) for e in bf_errors])
|
2006-12-07 14:10:31 +08:00
|
|
|
hidden_fields.append(unicode(bf))
|
2006-12-01 01:07:40 +08:00
|
|
|
else:
|
2006-12-07 23:49:05 +08:00
|
|
|
if errors_on_separate_row and bf_errors:
|
|
|
|
output.append(error_row % bf_errors)
|
2007-04-27 22:27:07 +08:00
|
|
|
if bf.label:
|
|
|
|
label = escape(bf.label)
|
|
|
|
# Only add a colon if the label does not end in punctuation.
|
|
|
|
if label[-1] not in ':?.!':
|
|
|
|
label += ':'
|
|
|
|
label = bf.label_tag(label) or ''
|
|
|
|
else:
|
|
|
|
label = ''
|
2007-01-29 06:10:04 +08:00
|
|
|
if field.help_text:
|
|
|
|
help_text = help_text_html % field.help_text
|
|
|
|
else:
|
|
|
|
help_text = u''
|
|
|
|
output.append(normal_row % {'errors': bf_errors, 'label': label, 'field': unicode(bf), 'help_text': help_text})
|
2006-12-07 13:35:39 +08:00
|
|
|
if top_errors:
|
2006-12-07 14:59:07 +08:00
|
|
|
output.insert(0, error_row % top_errors)
|
|
|
|
if hidden_fields: # Insert any hidden fields in the last row.
|
2006-12-07 14:06:58 +08:00
|
|
|
str_hidden = u''.join(hidden_fields)
|
|
|
|
if output:
|
2006-12-07 14:59:07 +08:00
|
|
|
last_row = output[-1]
|
|
|
|
# Chop off the trailing row_ender (e.g. '</td></tr>') and insert the hidden fields.
|
|
|
|
output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender
|
|
|
|
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)
|
2006-11-16 09:16:33 +08:00
|
|
|
return u'\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>."
|
2007-01-29 06:10:04 +08:00
|
|
|
return self._html_output(u'<tr><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>', u'<tr><td colspan="2">%s</td></tr>', '</td></tr>', u'<br />%s', 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>."
|
2007-01-29 06:10:04 +08:00
|
|
|
return self._html_output(u'<li>%(errors)s%(label)s %(field)s%(help_text)s</li>', u'<li>%s</li>', '</li>', u' %s', False)
|
2006-12-07 14:34:37 +08:00
|
|
|
|
|
|
|
def as_p(self):
|
|
|
|
"Returns this form rendered as HTML <p>s."
|
2007-01-29 06:10:04 +08:00
|
|
|
return self._html_output(u'<p>%(label)s %(field)s%(help_text)s</p>', u'<p>%s</p>', '</p>', u' %s', 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
|
|
|
"""
|
2006-11-27 12:56:33 +08:00
|
|
|
return self.errors.get(NON_FIELD_ERRORS, ErrorList())
|
2006-11-27 12:49:26 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def full_clean(self):
|
|
|
|
"""
|
|
|
|
Cleans all of self.data and populates self.__errors and self.clean_data.
|
|
|
|
"""
|
2006-10-29 04:34:37 +08:00
|
|
|
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
|
|
|
self.__errors = errors
|
|
|
|
return
|
2007-01-04 14:25:53 +08:00
|
|
|
self.clean_data = {}
|
2006-10-29 04:34:37 +08:00
|
|
|
for name, field in self.fields.items():
|
2006-11-30 01:00:34 +08:00
|
|
|
# value_from_datadict() gets the data from the dictionary.
|
|
|
|
# Each widget type knows how to retrieve its own data, because some
|
|
|
|
# widgets split data over several HTML fields.
|
2006-12-12 13:55:39 +08:00
|
|
|
value = field.widget.value_from_datadict(self.data, self.add_prefix(name))
|
2006-10-29 04:34:37 +08:00
|
|
|
try:
|
2006-11-05 04:49:59 +08:00
|
|
|
value = field.clean(value)
|
|
|
|
self.clean_data[name] = value
|
|
|
|
if hasattr(self, 'clean_%s' % name):
|
|
|
|
value = getattr(self, 'clean_%s' % name)()
|
|
|
|
self.clean_data[name] = value
|
2006-10-29 04:34:37 +08:00
|
|
|
except ValidationError, e:
|
|
|
|
errors[name] = e.messages
|
2006-11-05 04:49:59 +08:00
|
|
|
try:
|
|
|
|
self.clean_data = self.clean()
|
|
|
|
except ValidationError, e:
|
|
|
|
errors[NON_FIELD_ERRORS] = e.messages
|
|
|
|
if errors:
|
2007-01-04 14:25:53 +08:00
|
|
|
delattr(self, 'clean_data')
|
2006-10-29 04:34:37 +08:00
|
|
|
self.__errors = errors
|
|
|
|
|
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
|
|
|
"""
|
|
|
|
return self.clean_data
|
|
|
|
|
2006-12-15 13:35:19 +08:00
|
|
|
class Form(BaseForm):
|
|
|
|
"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.
|
|
|
|
__metaclass__ = DeclarativeFieldsMetaclass
|
|
|
|
|
2006-12-06 04:08:27 +08:00
|
|
|
class BoundField(StrAndUnicode):
|
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)
|
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
|
|
|
|
2006-12-06 04:08:27 +08:00
|
|
|
def __unicode__(self):
|
2006-10-29 04:34:37 +08:00
|
|
|
"Renders this field as an HTML widget."
|
|
|
|
# Use the 'widget' attribute on the field to determine which type
|
|
|
|
# of HTML widget to use.
|
2006-12-06 02:48:49 +08:00
|
|
|
value = self.as_widget(self.field.widget)
|
2006-11-27 02:44:58 +08:00
|
|
|
if not isinstance(value, basestring):
|
|
|
|
# Some Widget render() methods -- notably RadioSelect -- return a
|
2007-04-04 21:57:14 +08:00
|
|
|
# "special" object rather than a string. Call __unicode__() on that
|
2006-11-27 02:44:58 +08:00
|
|
|
# object to get its rendered value.
|
2007-04-04 21:57:14 +08:00
|
|
|
value = unicode(value)
|
2006-11-27 02:44:58 +08:00
|
|
|
return value
|
2006-10-29 04:34:37 +08:00
|
|
|
|
|
|
|
def _errors(self):
|
|
|
|
"""
|
|
|
|
Returns an ErrorList for this field. Returns an empty ErrorList
|
|
|
|
if there are none.
|
|
|
|
"""
|
2006-12-07 13:19:01 +08:00
|
|
|
return self.form.errors.get(self.name, ErrorList())
|
2006-10-29 04:34:37 +08:00
|
|
|
errors = property(_errors)
|
|
|
|
|
|
|
|
def as_widget(self, widget, attrs=None):
|
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:
|
2006-11-16 07:09:10 +08:00
|
|
|
attrs['id'] = auto_id
|
2007-01-05 08:04:38 +08:00
|
|
|
if not self.form.is_bound:
|
2007-01-09 12:39:44 +08:00
|
|
|
data = self.form.initial.get(self.name, self.field.initial)
|
2006-12-28 08:01:52 +08:00
|
|
|
else:
|
|
|
|
data = self.data
|
|
|
|
return widget.render(self.html_name, data, attrs=attrs)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
|
|
|
def as_text(self, attrs=None):
|
|
|
|
"""
|
|
|
|
Returns a string of HTML for representing this as an <input type="text">.
|
|
|
|
"""
|
|
|
|
return self.as_widget(TextInput(), attrs)
|
|
|
|
|
|
|
|
def as_textarea(self, attrs=None):
|
|
|
|
"Returns a string of HTML for representing this as a <textarea>."
|
|
|
|
return self.as_widget(Textarea(), attrs)
|
2006-11-16 07:09:10 +08:00
|
|
|
|
2006-11-30 11:58:25 +08:00
|
|
|
def as_hidden(self, attrs=None):
|
|
|
|
"""
|
|
|
|
Returns a string of HTML for representing this as an <input type="hidden">.
|
|
|
|
"""
|
2007-01-09 13:12:25 +08:00
|
|
|
return self.as_widget(self.field.hidden_widget(), attrs)
|
2006-11-30 11:58:25 +08:00
|
|
|
|
2006-11-30 05:48:58 +08:00
|
|
|
def _data(self):
|
2006-12-28 08:01:52 +08:00
|
|
|
"""
|
|
|
|
Returns the data for this BoundField, or None if it wasn't given.
|
|
|
|
"""
|
2006-12-24 11:36:49 +08:00
|
|
|
return self.field.widget.value_from_datadict(self.form.data, self.html_name)
|
2006-11-30 05:48:58 +08:00
|
|
|
data = property(_data)
|
|
|
|
|
2007-01-21 04:31:17 +08:00
|
|
|
def label_tag(self, contents=None, attrs=None):
|
2006-11-29 08:49:27 +08:00
|
|
|
"""
|
|
|
|
Wraps the given contents in a <label>, if the field has an ID attribute.
|
|
|
|
Does not HTML-escape the contents. If contents aren't given, uses the
|
2006-12-09 04:06:12 +08:00
|
|
|
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.
|
2006-11-29 08:49:27 +08:00
|
|
|
"""
|
2006-12-09 04:06:12 +08:00
|
|
|
contents = contents or escape(self.label)
|
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_:
|
2007-01-21 04:31:17 +08:00
|
|
|
attrs = attrs and flatatt(attrs) or ''
|
|
|
|
contents = '<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, contents)
|
2006-11-29 08:49:27 +08:00
|
|
|
return contents
|
2006-11-27 12:23:20 +08:00
|
|
|
|
2006-12-01 01:07:40 +08:00
|
|
|
def _is_hidden(self):
|
|
|
|
"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
|
|
|
is_hidden = property(_is_hidden)
|
|
|
|
|
2006-11-16 07:09:10 +08:00
|
|
|
def _auto_id(self):
|
|
|
|
"""
|
|
|
|
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
|
2006-11-16 07:09:10 +08:00
|
|
|
if auto_id and '%s' in str(auto_id):
|
2006-12-14 07:03:19 +08:00
|
|
|
return str(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 ''
|
|
|
|
auto_id = property(_auto_id)
|