diff options
| author | Adrian Holovaty <adrian@holovaty.com> | 2006-11-04 20:49:59 +0000 |
|---|---|---|
| committer | Adrian Holovaty <adrian@holovaty.com> | 2006-11-04 20:49:59 +0000 |
| commit | 46b0713315020d63fa8ce7c4ea14d99daf256e47 (patch) | |
| tree | d9dd9da8a3133a5657e7118253ff599bfca95480 /django | |
| parent | 88029f770010b96bb4a50de038a125be3104d09d (diff) | |
django.newforms: Implemented hook for validation not tied to a particular field. Renamed to_python() to clean() -- it's just...cleaner. Added Form.as_table(), Form.as_url(), Form.as_table_with_errors() and Form.as_ul_with_errors(). Added ComboField. Updated all unit tests.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@3978 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django')
| -rw-r--r-- | django/newforms/__init__.py | 2 | ||||
| -rw-r--r-- | django/newforms/fields.py | 54 | ||||
| -rw-r--r-- | django/newforms/forms.py | 104 |
3 files changed, 121 insertions, 39 deletions
diff --git a/django/newforms/__init__.py b/django/newforms/__init__.py index 9d12c55ae9..2a472d7b39 100644 --- a/django/newforms/__init__.py +++ b/django/newforms/__init__.py @@ -2,7 +2,6 @@ Django validation and HTML form handling. TODO: - Validation not tied to a particular field Default value for field Field labels Nestable Forms @@ -11,6 +10,7 @@ TODO: "This form field requires foo.js" and form.js_includes() """ +from util import ValidationError from widgets import * from fields import * from forms import Form diff --git a/django/newforms/fields.py b/django/newforms/fields.py index 83867dccc3..79558bbf9e 100644 --- a/django/newforms/fields.py +++ b/django/newforms/fields.py @@ -14,6 +14,7 @@ __all__ = ( 'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField', 'RegexField', 'EmailField', 'URLField', 'BooleanField', 'ChoiceField', 'MultipleChoiceField', + 'ComboField', ) # These values, if given to to_python(), will trigger the self.required check. @@ -34,9 +35,9 @@ class Field(object): widget = widget() self.widget = widget - def to_python(self, value): + def clean(self, value): """ - Validates the given value and returns its "normalized" value as an + Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors. @@ -50,9 +51,9 @@ class CharField(Field): Field.__init__(self, required, widget) self.max_length, self.min_length = max_length, min_length - def to_python(self, value): + def clean(self, value): "Validates max_length and min_length. Returns a Unicode object." - Field.to_python(self, value) + Field.clean(self, value) if value in EMPTY_VALUES: value = u'' if not isinstance(value, basestring): value = unicode(str(value), DEFAULT_ENCODING) @@ -65,12 +66,12 @@ class CharField(Field): return value class IntegerField(Field): - def to_python(self, value): + def clean(self, value): """ Validates that int() can be called on the input. Returns the result of int(). """ - super(IntegerField, self).to_python(value) + super(IntegerField, self).clean(value) try: return int(value) except (ValueError, TypeError): @@ -89,12 +90,12 @@ class DateField(Field): Field.__init__(self, required, widget) self.input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS - def to_python(self, value): + def clean(self, value): """ Validates that the input can be converted to a date. Returns a Python datetime.date object. """ - Field.to_python(self, value) + Field.clean(self, value) if value in EMPTY_VALUES: return None if isinstance(value, datetime.datetime): @@ -125,12 +126,12 @@ class DateTimeField(Field): Field.__init__(self, required, widget) self.input_formats = input_formats or DEFAULT_DATETIME_INPUT_FORMATS - def to_python(self, value): + def clean(self, value): """ Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object. """ - Field.to_python(self, value) + Field.clean(self, value) if value in EMPTY_VALUES: return None if isinstance(value, datetime.datetime): @@ -157,12 +158,12 @@ class RegexField(Field): self.regex = regex self.error_message = error_message or u'Enter a valid value.' - def to_python(self, value): + def clean(self, value): """ Validates that the input matches the regular expression. Returns a Unicode object. """ - Field.to_python(self, value) + Field.clean(self, value) if value in EMPTY_VALUES: value = u'' if not isinstance(value, basestring): value = unicode(str(value), DEFAULT_ENCODING) @@ -192,8 +193,8 @@ class URLField(RegexField): RegexField.__init__(self, url_re, u'Enter a valid URL.', required, widget) self.verify_exists = verify_exists - def to_python(self, value): - value = RegexField.to_python(self, value) + def clean(self, value): + value = RegexField.clean(self, value) if self.verify_exists: import urllib2 try: @@ -207,9 +208,9 @@ class URLField(RegexField): class BooleanField(Field): widget = CheckboxInput - def to_python(self, value): + def clean(self, value): "Returns a Python boolean object." - Field.to_python(self, value) + Field.clean(self, value) return bool(value) class ChoiceField(Field): @@ -219,11 +220,11 @@ class ChoiceField(Field): Field.__init__(self, required, widget) self.choices = choices - def to_python(self, value): + def clean(self, value): """ Validates that the input is in self.choices. """ - value = Field.to_python(self, value) + value = Field.clean(self, value) if value in EMPTY_VALUES: value = u'' if not isinstance(value, basestring): value = unicode(str(value), DEFAULT_ENCODING) @@ -238,7 +239,7 @@ class MultipleChoiceField(ChoiceField): def __init__(self, choices=(), required=True, widget=SelectMultiple): ChoiceField.__init__(self, choices, required, widget) - def to_python(self, value): + def clean(self, value): """ Validates that the input is a list or tuple. """ @@ -259,3 +260,18 @@ class MultipleChoiceField(ChoiceField): if val not in valid_values: raise ValidationError(u'Select a valid choice. %s is not one of the available choices.' % val) return new_value + +class ComboField(Field): + def __init__(self, fields=(), required=True, widget=None): + Field.__init__(self, required, widget) + self.fields = fields + + def clean(self, value): + """ + Validates the given value against all of self.fields, which is a + list of Field instances. + """ + Field.clean(self, value) + for field in self.fields: + value = field.clean(value) + return value diff --git a/django/newforms/forms.py b/django/newforms/forms.py index 34e13c6542..e490d0d5f9 100644 --- a/django/newforms/forms.py +++ b/django/newforms/forms.py @@ -6,6 +6,13 @@ from fields import Field from widgets import TextInput, Textarea from util import ErrorDict, ErrorList, ValidationError +NON_FIELD_ERRORS = '__all__' + +def pretty_name(name): + "Converts 'first_name' to 'First name'" + name = name[0].upper() + name[1:] + return name.replace('_', ' ') + class DeclarativeFieldsMetaclass(type): "Metaclass that converts Field attributes to a dictionary called 'fields'." def __new__(cls, name, bases, attrs): @@ -18,22 +25,33 @@ class Form(object): def __init__(self, data=None): # TODO: prefix stuff self.data = data or {} - self.__data_python = None # Stores the data after to_python() has been called. - self.__errors = None # Stores the errors after to_python() has been called. + self.clean_data = None # Stores the data after clean() has been called. + self.__errors = None # Stores the errors after clean() has been called. + + def __str__(self): + return self.as_table() def __iter__(self): for name, field in self.fields.items(): yield BoundField(self, field, name) - def to_python(self): + 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) + + def clean(self): if self.__errors is None: - self._validate() - return self.__data_python + self.full_clean() + return self.clean_data def errors(self): "Returns an ErrorDict for self.data" if self.__errors is None: - self._validate() + self.full_clean() return self.__errors def is_valid(self): @@ -44,27 +62,75 @@ class Form(object): """ return not bool(self.errors()) - 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) + def as_table(self): + "Returns this form rendered as an HTML <table>." + output = u'\n'.join(['<tr><td>%s:</td><td>%s</td></tr>' % (pretty_name(name), BoundField(self, field, name)) for name, field in self.fields.items()]) + return '<table>\n%s\n</table>' % output - def _validate(self): - data_python = {} + def as_ul(self): + "Returns this form rendered as an HTML <ul>." + output = u'\n'.join(['<li>%s: %s</li>' % (pretty_name(name), BoundField(self, field, name)) for name, field in self.fields.items()]) + return '<ul>\n%s\n</ul>' % output + + def as_table_with_errors(self): + "Returns this form rendered as an HTML <table>, with errors." + output = [] + if self.errors().get(NON_FIELD_ERRORS): + # Errors not corresponding to a particular field are displayed at the top. + output.append('<tr><td colspan="2"><ul>%s</ul></td></tr>' % '\n'.join(['<li>%s</li>' % e for e in self.errors()[NON_FIELD_ERRORS]])) + for name, field in self.fields.items(): + bf = BoundField(self, field, name) + if bf.errors: + output.append('<tr><td colspan="2"><ul>%s</ul></td></tr>' % '\n'.join(['<li>%s</li>' % e for e in bf.errors])) + output.append('<tr><td>%s:</td><td>%s</td></tr>' % (pretty_name(name), bf)) + return '<table>\n%s\n</table>' % '\n'.join(output) + + def as_ul_with_errors(self): + "Returns this form rendered as an HTML <ul>, with errors." + output = [] + if self.errors().get(NON_FIELD_ERRORS): + # Errors not corresponding to a particular field are displayed at the top. + output.append('<li><ul>%s</ul></li>' % '\n'.join(['<li>%s</li>' % e for e in self.errors()[NON_FIELD_ERRORS]])) + for name, field in self.fields.items(): + bf = BoundField(self, field, name) + line = '<li>' + if bf.errors: + line += '<ul>%s</ul>' % '\n'.join(['<li>%s</li>' % e for e in bf.errors]) + line += '%s: %s</li>' % (pretty_name(name), bf) + output.append(line) + return '<ul>\n%s\n</ul>' % '\n'.join(output) + + def full_clean(self): + """ + Cleans all of self.data and populates self.__errors and self.clean_data. + """ + self.clean_data = {} errors = ErrorDict() for name, field in self.fields.items(): + value = self.data.get(name, None) try: - value = field.to_python(self.data.get(name, None)) - data_python[name] = value + 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 except ValidationError, e: errors[name] = e.messages - if not errors: # Only set self.data_python if there weren't errors. - self.__data_python = data_python + try: + self.clean_data = self.clean() + except ValidationError, e: + errors[NON_FIELD_ERRORS] = e.messages + if errors: + self.clean_data = None self.__errors = errors + def clean(self): + """ + Hook for doing any extra form-wide cleaning after Field.clean() been + called on every field. + """ + return self.clean_data + class BoundField(object): "A Field plus data" def __init__(self, form, field, name): |
