From 55d7f6519c8d13a685cff3f9873b5784fc511a87 Mon Sep 17 00:00:00 2001 From: Jason Pellerin Date: Mon, 4 Dec 2006 21:12:29 +0000 Subject: [multi-db] Merged trunk to [4158]. Some tests still failing. git-svn-id: http://code.djangoproject.com/svn/django/branches/multiple-db-support@4159 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/newforms/__init__.py | 13 +---- django/newforms/fields.py | 17 +++++- django/newforms/forms.py | 130 +++++++++++++++++++++++++++++++------------- django/newforms/models.py | 13 +++++ django/newforms/widgets.py | 85 ++++++++++++++++++++++++++--- 5 files changed, 197 insertions(+), 61 deletions(-) create mode 100644 django/newforms/models.py (limited to 'django/newforms') diff --git a/django/newforms/__init__.py b/django/newforms/__init__.py index 2a472d7b39..a445a21bfb 100644 --- a/django/newforms/__init__.py +++ b/django/newforms/__init__.py @@ -14,15 +14,4 @@ from util import ValidationError from widgets import * from fields import * from forms import Form - -########################## -# DATABASE API SHORTCUTS # -########################## - -def form_for_model(model): - "Returns a Form instance for the given Django model class." - raise NotImplementedError - -def form_for_fields(field_list): - "Returns a Form instance for the given list of Django database field instances." - raise NotImplementedError +from models import * diff --git a/django/newforms/fields.py b/django/newforms/fields.py index 40fc18bd3e..b3d44c24ae 100644 --- a/django/newforms/fields.py +++ b/django/newforms/fields.py @@ -76,6 +76,8 @@ class IntegerField(Field): of int(). """ super(IntegerField, self).clean(value) + if not self.required and value in EMPTY_VALUES: + return u'' try: return int(value) except (ValueError, TypeError): @@ -170,6 +172,8 @@ class RegexField(Field): Field.clean(self, value) if value in EMPTY_VALUES: value = u'' value = smart_unicode(value) + if not self.required and value == u'': + return value if not self.regex.search(value): raise ValidationError(self.error_message) return value @@ -246,6 +250,8 @@ class ChoiceField(Field): value = Field.clean(self, value) if value in EMPTY_VALUES: value = u'' value = smart_unicode(value) + if not self.required and value == u'': + return value valid_values = set([str(k) for k, v in self.choices]) if value not in valid_values: raise ValidationError(u'Select a valid choice. %s is not one of the available choices.' % value) @@ -259,10 +265,12 @@ class MultipleChoiceField(ChoiceField): """ Validates that the input is a list or tuple. """ - if not isinstance(value, (list, tuple)): - raise ValidationError(u'Enter a list of values.') if self.required and not value: raise ValidationError(u'This field is required.') + elif not self.required and not value: + return [] + if not isinstance(value, (list, tuple)): + raise ValidationError(u'Enter a list of values.') new_value = [] for val in value: val = smart_unicode(val) @@ -277,6 +285,11 @@ class MultipleChoiceField(ChoiceField): class ComboField(Field): def __init__(self, fields=(), required=True, widget=None): Field.__init__(self, required, widget) + # Set 'required' to False on the individual fields, because the + # required validation will be handled by ComboField, not by those + # individual fields. + for f in fields: + f.required = False self.fields = fields def clean(self, value): diff --git a/django/newforms/forms.py b/django/newforms/forms.py index b8264fb691..4bc6173249 100644 --- a/django/newforms/forms.py +++ b/django/newforms/forms.py @@ -3,8 +3,9 @@ Form classes """ from django.utils.datastructures import SortedDict +from django.utils.html import escape from fields import Field -from widgets import TextInput, Textarea +from widgets import TextInput, Textarea, HiddenInput from util import ErrorDict, ErrorList, ValidationError NON_FIELD_ERRORS = '__all__' @@ -36,6 +37,7 @@ class Form(object): __metaclass__ = DeclarativeFieldsMetaclass def __init__(self, data=None, auto_id=False): # TODO: prefix stuff + self.ignore_errors = data is None self.data = data or {} self.auto_id = auto_id self.clean_data = None # Stores the data after clean() has been called. @@ -56,69 +58,78 @@ class Form(object): raise KeyError('Key %r not found in Form' % name) return BoundField(self, field, name) - def clean(self): - if self.__errors is None: - self.full_clean() - return self.clean_data - - def errors(self): + def _errors(self): "Returns an ErrorDict for self.data" if self.__errors is None: self.full_clean() return self.__errors + errors = property(_errors) def is_valid(self): """ - Returns True if the form has no errors. Otherwise, False. This exists - solely for convenience, so client code can use positive logic rather - than confusing negative logic ("if not form.errors()"). + Returns True if the form has no errors. Otherwise, False. If errors are + being ignored, returns False. """ - return not bool(self.errors()) + return not self.ignore_errors and not bool(self.errors) def as_table(self): "Returns this form rendered as HTML s -- excluding the
." - return u'\n'.join(['%s:%s' % (pretty_name(name), BoundField(self, field, name)) for name, field in self.fields.items()]) - - def as_ul(self): - "Returns this form rendered as HTML
  • s -- excluding the ." - return u'\n'.join(['
  • %s: %s
  • ' % (pretty_name(name), BoundField(self, field, name)) for name, field in self.fields.items()]) - - def as_table_with_errors(self): - "Returns this form rendered as HTML s, with errors." output = [] - if self.errors().get(NON_FIELD_ERRORS): + if self.errors.get(NON_FIELD_ERRORS): # Errors not corresponding to a particular field are displayed at the top. - output.append('' % '\n'.join(['
  • %s
  • ' % e for e in self.errors()[NON_FIELD_ERRORS]])) + output.append(u'%s' % self.non_field_errors()) for name, field in self.fields.items(): bf = BoundField(self, field, name) - if bf.errors: - output.append('' % '\n'.join(['
  • %s
  • ' % e for e in bf.errors])) - output.append('%s:%s' % (pretty_name(name), bf)) + if bf.is_hidden: + if bf.errors: + new_errors = ErrorList(['(Hidden field %s) %s' % (name, e) for e in bf.errors]) + output.append(u'%s' % new_errors) + output.append(str(bf)) + else: + if bf.errors: + output.append(u'%s' % bf.errors) + output.append(u'%s%s' % (bf.label_tag(escape(bf.verbose_name+':')), bf)) return u'\n'.join(output) - def as_ul_with_errors(self): - "Returns this form rendered as HTML
  • s, with errors." + def as_ul(self): + "Returns this form rendered as HTML
  • s -- excluding the ." output = [] - if self.errors().get(NON_FIELD_ERRORS): + if self.errors.get(NON_FIELD_ERRORS): # Errors not corresponding to a particular field are displayed at the top. - output.append('
  • ' % '\n'.join(['
  • %s
  • ' % e for e in self.errors()[NON_FIELD_ERRORS]])) + output.append(u'
  • %s
  • ' % self.non_field_errors()) for name, field in self.fields.items(): bf = BoundField(self, field, name) - line = '
  • ' - if bf.errors: - line += '' % '\n'.join(['
  • %s
  • ' % e for e in bf.errors]) - line += '%s: %s' % (pretty_name(name), bf) - output.append(line) + if bf.is_hidden: + if bf.errors: + new_errors = ErrorList(['(Hidden field %s) %s' % (name, e) for e in bf.errors]) + output.append(u'
  • %s
  • ' % new_errors) + output.append(str(bf)) + else: + output.append(u'
  • %s%s %s
  • ' % (bf.errors, bf.label_tag(escape(bf.verbose_name+':')), bf)) return u'\n'.join(output) + def non_field_errors(self): + """ + 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. + """ + return self.errors.get(NON_FIELD_ERRORS, ErrorList()) + def full_clean(self): """ Cleans all of self.data and populates self.__errors and self.clean_data. """ self.clean_data = {} errors = ErrorDict() + if self.ignore_errors: # Stop further processing. + self.__errors = errors + return for name, field in self.fields.items(): - value = self.data.get(name, None) + # 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) try: value = field.clean(value) self.clean_data[name] = value @@ -138,7 +149,9 @@ class Form(object): def clean(self): """ Hook for doing any extra form-wide cleaning after Field.clean() been - called on every field. + 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__'. """ return self.clean_data @@ -153,7 +166,13 @@ class BoundField(object): "Renders this field as an HTML widget." # Use the 'widget' attribute on the field to determine which type # of HTML widget to use. - return self.as_widget(self._field.widget) + value = self.as_widget(self._field.widget) + 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 def _errors(self): """ @@ -161,7 +180,7 @@ class BoundField(object): if there are none. """ try: - return self._form.errors()[self._name] + return self._form.errors[self._name] except KeyError: return ErrorList() errors = property(_errors) @@ -169,9 +188,9 @@ class BoundField(object): def as_widget(self, widget, attrs=None): attrs = attrs or {} auto_id = self.auto_id - if not attrs.has_key('id') and not widget.attrs.has_key('id') and auto_id: + if auto_id and not attrs.has_key('id') and not widget.attrs.has_key('id'): attrs['id'] = auto_id - return widget.render(self._name, self._form.data.get(self._name, None), attrs=attrs) + return widget.render(self._name, self.data, attrs=attrs) def as_text(self, attrs=None): """ @@ -183,6 +202,39 @@ class BoundField(object): "Returns a string of HTML for representing this as a ' % (flatatt(final_attrs), escape(value)) class CheckboxInput(Widget): + def __init__(self, attrs=None, check_test=bool): + # check_test is a callable that takes a value and returns True + # if the checkbox should be checked for that value. + self.attrs = attrs or {} + self.check_test = check_test + def render(self, name, value, attrs=None): final_attrs = self.build_attrs(attrs, type='checkbox', name=name) - if value: final_attrs['checked'] = 'checked' + try: + result = self.check_test(value) + except: # Silently catch exceptions + result = False + if result: + final_attrs['checked'] = 'checked' + if value not in ('', True, False, None): + final_attrs['value'] = smart_unicode(value) # Only add the 'value' attribute if a value is non-empty. return u'' % flatatt(final_attrs) class Select(Widget): @@ -111,10 +148,11 @@ class SelectMultiple(Widget): class RadioInput(object): "An object used by RadioFieldRenderer that represents a single ." - def __init__(self, name, value, attrs, choice): + def __init__(self, name, value, attrs, choice, index): self.name, self.value = name, value - self.attrs = attrs or {} + self.attrs = attrs self.choice_value, self.choice_label = choice + self.index = index def __str__(self): return u'' % (self.tag(), self.choice_label) @@ -123,6 +161,8 @@ class RadioInput(object): return self.value == smart_unicode(self.choice_value) def tag(self): + if self.attrs.has_key('id'): + self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index) final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value) if self.is_checked(): final_attrs['checked'] = 'checked' @@ -135,8 +175,8 @@ class RadioFieldRenderer(object): self.choices = choices def __iter__(self): - for choice in self.choices: - yield RadioInput(self.name, self.value, self.attrs, choice) + for i, choice in enumerate(self.choices): + yield RadioInput(self.name, self.value, self.attrs.copy(), choice, i) def __str__(self): "Outputs a