2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Form classes
|
|
|
|
"""
|
|
|
|
|
2006-11-24 01:40:33 +08:00
|
|
|
from django.utils.datastructures import SortedDict
|
2006-11-29 08:49:27 +08:00
|
|
|
from django.utils.html import escape
|
2006-10-29 04:34:37 +08:00
|
|
|
from fields import Field
|
2006-11-30 11:58:25 +08:00
|
|
|
from widgets import TextInput, Textarea, HiddenInput
|
2006-12-06 04:08:27 +08:00
|
|
|
from util import StrAndUnicode, ErrorDict, ErrorList, ValidationError
|
2006-10-29 04:34:37 +08:00
|
|
|
|
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))
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class DeclarativeFieldsMetaclass(type):
|
|
|
|
"Metaclass that converts Field attributes to a dictionary called 'fields'."
|
|
|
|
def __new__(cls, name, bases, attrs):
|
2006-11-24 01:40:33 +08:00
|
|
|
fields = [(name, attrs.pop(name)) for name, obj in attrs.items() if isinstance(obj, Field)]
|
|
|
|
fields.sort(lambda x, y: cmp(x[1].creation_counter, y[1].creation_counter))
|
|
|
|
attrs['fields'] = SortedDictFromList(fields)
|
2006-10-29 04:34:37 +08:00
|
|
|
return type.__new__(cls, name, bases, attrs)
|
|
|
|
|
2006-12-06 04:08:27 +08:00
|
|
|
class Form(StrAndUnicode):
|
2006-10-29 04:34:37 +08:00
|
|
|
"A collection of Fields, plus their associated data."
|
|
|
|
__metaclass__ = DeclarativeFieldsMetaclass
|
|
|
|
|
2006-11-16 07:09:10 +08:00
|
|
|
def __init__(self, data=None, auto_id=False): # TODO: prefix stuff
|
2006-11-27 11:49:19 +08:00
|
|
|
self.ignore_errors = data is 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-11-05 04:49:59 +08:00
|
|
|
self.clean_data = None # Stores the data after clean() has been called.
|
|
|
|
self.__errors = None # Stores the errors after clean() has been called.
|
|
|
|
|
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
|
|
|
"""
|
2006-11-27 11:49:19 +08:00
|
|
|
return not self.ignore_errors and not bool(self.errors)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def as_table(self):
|
2006-11-16 09:16:33 +08:00
|
|
|
"Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
|
2006-12-07 13:35:39 +08:00
|
|
|
top_errors = self.non_field_errors()
|
2006-11-05 04:49:59 +08:00
|
|
|
output = []
|
|
|
|
for name, field in self.fields.items():
|
|
|
|
bf = BoundField(self, field, name)
|
2006-12-07 13:45:22 +08:00
|
|
|
bf_errors = bf.errors # 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-01 01:07:40 +08:00
|
|
|
output.append(str(bf))
|
|
|
|
else:
|
2006-12-07 13:35:39 +08:00
|
|
|
if bf_errors:
|
|
|
|
output.append(u'<tr><td colspan="2">%s</td></tr>' % bf_errors)
|
2006-12-01 01:07:40 +08:00
|
|
|
output.append(u'<tr><td>%s</td><td>%s</td></tr>' % (bf.label_tag(escape(bf.verbose_name+':')), bf))
|
2006-12-07 13:35:39 +08:00
|
|
|
if top_errors:
|
|
|
|
output.insert(0, u'<tr><td colspan="2">%s</td></tr>' % top_errors)
|
2006-11-16 09:16:33 +08:00
|
|
|
return u'\n'.join(output)
|
2006-11-05 04:49:59 +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>."
|
2006-12-07 13:35:39 +08:00
|
|
|
top_errors = self.non_field_errors()
|
2006-11-05 04:49:59 +08:00
|
|
|
output = []
|
|
|
|
for name, field in self.fields.items():
|
|
|
|
bf = BoundField(self, field, name)
|
2006-12-01 01:07:40 +08:00
|
|
|
if bf.is_hidden:
|
2006-12-07 13:35:39 +08:00
|
|
|
new_errors = bf.errors # Cache in local variable.
|
|
|
|
if new_errors:
|
|
|
|
top_errors.extend(['(Hidden field %s) %s' % (name, e) for e in new_errors])
|
2006-12-07 13:45:22 +08:00
|
|
|
output.append(unicode(bf))
|
2006-12-01 01:07:40 +08:00
|
|
|
else:
|
|
|
|
output.append(u'<li>%s%s %s</li>' % (bf.errors, bf.label_tag(escape(bf.verbose_name+':')), bf))
|
2006-12-07 13:35:39 +08:00
|
|
|
if top_errors:
|
|
|
|
output.insert(0, u'<li>%s</li>' % top_errors)
|
2006-11-16 09:16:33 +08:00
|
|
|
return u'\n'.join(output)
|
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.
|
|
|
|
"""
|
|
|
|
self.clean_data = {}
|
2006-10-29 04:34:37 +08:00
|
|
|
errors = ErrorDict()
|
2006-11-27 11:49:19 +08:00
|
|
|
if self.ignore_errors: # Stop further processing.
|
|
|
|
self.__errors = errors
|
|
|
|
return
|
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.
|
|
|
|
value = field.widget.value_from_datadict(self.data, 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:
|
|
|
|
self.clean_data = None
|
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-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
|
|
|
|
self.name = name
|
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
|
|
|
|
# "special" object rather than a string. Call the __str__() on that
|
|
|
|
# object to get its rendered value.
|
|
|
|
value = value.__str__()
|
|
|
|
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
|
2006-11-27 13:02:21 +08:00
|
|
|
if auto_id and not attrs.has_key('id') and not widget.attrs.has_key('id'):
|
2006-11-16 07:09:10 +08:00
|
|
|
attrs['id'] = auto_id
|
2006-12-06 02:48:49 +08:00
|
|
|
return widget.render(self.name, self.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">.
|
|
|
|
"""
|
|
|
|
return self.as_widget(HiddenInput(), attrs)
|
|
|
|
|
2006-11-30 05:48:58 +08:00
|
|
|
def _data(self):
|
|
|
|
"Returns the data for this BoundField, or None if it wasn't given."
|
2006-12-06 02:48:49 +08:00
|
|
|
return self.form.data.get(self.name, None)
|
2006-11-30 05:48:58 +08:00
|
|
|
data = property(_data)
|
|
|
|
|
2006-11-29 08:49:27 +08:00
|
|
|
def _verbose_name(self):
|
2006-12-06 02:48:49 +08:00
|
|
|
return pretty_name(self.name)
|
2006-11-29 08:49:27 +08:00
|
|
|
verbose_name = property(_verbose_name)
|
|
|
|
|
|
|
|
def label_tag(self, contents=None):
|
|
|
|
"""
|
|
|
|
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
|
|
|
|
field's HTML-escaped verbose_name.
|
|
|
|
"""
|
|
|
|
contents = contents or escape(self.verbose_name)
|
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_:
|
2006-11-29 09:40:27 +08:00
|
|
|
contents = '<label for="%s">%s</label>' % (widget.id_for_label(id_), 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-06 02:48:49 +08:00
|
|
|
return str(auto_id) % self.name
|
2006-11-16 07:09:10 +08:00
|
|
|
elif auto_id:
|
2006-12-06 02:48:49 +08:00
|
|
|
return self.name
|
2006-11-16 07:09:10 +08:00
|
|
|
return ''
|
|
|
|
auto_id = property(_auto_id)
|