Django

Code

Changeset 6693

Show
Ignore:
Timestamp:
11/18/07 06:07:25 (1 year ago)
Author:
mtredinnick
Message:

queryset-refactor: Fixed up a few problems from the previous merge from trunk.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/queryset-refactor/django/newforms/fields.py

    r6690 r6693  
    5050    creation_counter = 0 
    5151 
    52     def __init__(self, required=True, widget=None, label=None, initial=None, help_text=None): 
     52    def __init__(self, required=True, widget=None, label=None, initial=None, 
     53                 help_text=None, error_messages=None): 
    5354        # required -- Boolean that specifies whether the field is required. 
    5455        #             True by default. 
     
    107108        """ 
    108109        if self.required and value in EMPTY_VALUES: 
    109             raise ValidationError(ugettext(u'This field is required.')
     110            raise ValidationError(self.error_messages['required']
    110111        return value 
    111112 
     
    142143        value_length = len(value) 
    143144        if self.max_length is not None and value_length > self.max_length: 
    144             raise ValidationError(ugettext(u'Ensure this value has at most %(max)d characters (it has %(length)d).') % {'max': self.max_length, 'length': value_length}) 
     145            raise ValidationError(self.error_messages['max_length'] % {'max': self.max_length, 'length': value_length}) 
    145146        if self.min_length is not None and value_length < self.min_length: 
    146             raise ValidationError(ugettext(u'Ensure this value has at least %(min)d characters (it has %(length)d).') % {'min': self.min_length, 'length': value_length}) 
     147            raise ValidationError(self.error_messages['min_length'] % {'min': self.min_length, 'length': value_length}) 
    147148        return value 
    148149 
     
    174175            value = int(str(value)) 
    175176        except (ValueError, TypeError): 
    176             raise ValidationError(ugettext(u'Enter a whole number.')
     177            raise ValidationError(self.error_messages['invalid']
    177178        if self.max_value is not None and value > self.max_value: 
    178             raise ValidationError(ugettext(u'Ensure this value is less than or equal to %s.') % self.max_value) 
     179            raise ValidationError(self.error_messages['max_value'] % self.max_value) 
    179180        if self.min_value is not None and value < self.min_value: 
    180             raise ValidationError(ugettext(u'Ensure this value is greater than or equal to %s.') % self.min_value) 
     181            raise ValidationError(self.error_messages['min_value'] % self.min_value) 
    181182        return value 
    182183 
     
    203204            value = float(value) 
    204205        except (ValueError, TypeError): 
    205             raise ValidationError(ugettext('Enter a number.')
     206            raise ValidationError(self.error_messages['invalid']
    206207        if self.max_value is not None and value > self.max_value: 
    207             raise ValidationError(ugettext('Ensure this value is less than or equal to %s.') % self.max_value) 
     208            raise ValidationError(self.error_messages['max_value'] % self.max_value) 
    208209        if self.min_value is not None and value < self.min_value: 
    209             raise ValidationError(ugettext('Ensure this value is greater than or equal to %s.') % self.min_value) 
     210            raise ValidationError(self.error_messages['min_value'] % self.min_value) 
    210211        return value 
    211212 
     
    239240            value = Decimal(value) 
    240241        except DecimalException: 
    241             raise ValidationError(ugettext('Enter a number.')
     242            raise ValidationError(self.error_messages['invalid']
    242243        pieces = str(value).lstrip("-").split('.') 
    243244        decimals = (len(pieces) == 2) and len(pieces[1]) or 0 
    244245        digits = len(pieces[0]) 
    245246        if self.max_value is not None and value > self.max_value: 
    246             raise ValidationError(ugettext('Ensure this value is less than or equal to %s.') % self.max_value) 
     247            raise ValidationError(self.error_messages['max_value'] % self.max_value) 
    247248        if self.min_value is not None and value < self.min_value: 
    248             raise ValidationError(ugettext('Ensure this value is greater than or equal to %s.') % self.min_value) 
     249            raise ValidationError(self.error_messages['min_value'] % self.min_value) 
    249250        if self.max_digits is not None and (digits + decimals) > self.max_digits: 
    250             raise ValidationError(ugettext('Ensure that there are no more than %s digits in total.') % self.max_digits) 
     251            raise ValidationError(self.error_messages['max_digits'] % self.max_digits) 
    251252        if self.decimal_places is not None and decimals > self.decimal_places: 
    252             raise ValidationError(ugettext('Ensure that there are no more than %s decimal places.') % self.decimal_places) 
     253            raise ValidationError(self.error_messages['max_decimal_places'] % self.decimal_places) 
    253254        if self.max_digits is not None and self.decimal_places is not None and digits > (self.max_digits - self.decimal_places): 
    254             raise ValidationError(ugettext('Ensure that there are no more than %s digits before the decimal point.') % (self.max_digits - self.decimal_places)) 
     255            raise ValidationError(self.error_messages['max_whole_digits'] % (self.max_digits - self.decimal_places)) 
    255256        return value 
    256257 
     
    289290            except ValueError: 
    290291                continue 
    291         raise ValidationError(ugettext(u'Enter a valid date.')
     292        raise ValidationError(self.error_messages['invalid']
    292293 
    293294DEFAULT_TIME_INPUT_FORMATS = ( 
     
    320321            except ValueError: 
    321322                continue 
    322         raise ValidationError(ugettext(u'Enter a valid time.')
     323        raise ValidationError(self.error_messages['invalid']
    323324 
    324325DEFAULT_DATETIME_INPUT_FORMATS = ( 
     
    360361            # components: date and time. 
    361362            if len(value) != 2: 
    362                 raise ValidationError(ugettext(u'Enter a valid date/time.')
     363                raise ValidationError(self.error_messages['invalid']
    363364            value = '%s %s' % tuple(value) 
    364365        for format in self.input_formats: 
     
    367368            except ValueError: 
    368369                continue 
    369         raise ValidationError(ugettext(u'Enter a valid date/time.')
     370        raise ValidationError(self.error_messages['invalid']
    370371 
    371372class RegexField(CharField): 
     
    376377        'Enter a valid value' is too generic for you. 
    377378        """ 
     379        # error_message is just kept for backwards compatibility: 
     380        if error_message: 
     381            error_messages = kwargs.get('error_messages') or {} 
     382            error_messages['invalid'] = error_message 
     383            kwargs['error_messages'] = error_messages 
    378384        super(RegexField, self).__init__(max_length, min_length, *args, **kwargs) 
    379385        if isinstance(regex, basestring): 
    380386            regex = re.compile(regex) 
    381387        self.regex = regex 
    382         self.error_message = error_message or ugettext(u'Enter a valid value.') 
    383388 
    384389    def clean(self, value): 
     
    391396            return value 
    392397        if not self.regex.search(value): 
    393             raise ValidationError(self.error_message
     398            raise ValidationError(self.error_messages['invalid']
    394399        return value 
    395400 
     
    405410 
    406411    def __init__(self, max_length=None, min_length=None, *args, **kwargs): 
    407         RegexField.__init__(self, email_re, max_length, min_length, 
    408             ugettext(u'Enter a valid e-mail address.'), *args, **kwargs) 
     412        RegexField.__init__(self, email_re, max_length, min_length, *args, 
     413                            **kwargs) 
    409414 
    410415try: 
     
    446451            f = UploadedFile(data['filename'], data['content']) 
    447452        except TypeError: 
    448             raise ValidationError(ugettext(u"No file was submitted. Check the encoding type on the form.")
     453            raise ValidationError(self.error_messages['invalid']
    449454        except KeyError: 
    450             raise ValidationError(ugettext(u"No file was submitted.")
     455            raise ValidationError(self.error_messages['missing']
    451456        if not f.content: 
    452             raise ValidationError(ugettext(u"The submitted file is empty.")
     457            raise ValidationError(self.error_messages['empty']
    453458        return f 
    454459 
     
    478483            trial_image.verify() 
    479484        except Exception: # Python Imaging Library doesn't recognize it as an image 
    480             raise ValidationError(ugettext(u"Upload a valid image. The file you uploaded was either not an image or a corrupted image.")
     485            raise ValidationError(self.error_messages['invalid_image']
    481486        return f 
    482487 
     
    497502    def __init__(self, max_length=None, min_length=None, verify_exists=False, 
    498503            validator_user_agent=URL_VALIDATOR_USER_AGENT, *args, **kwargs): 
    499         super(URLField, self).__init__(url_re, max_length, min_length, ugettext(u'Enter a valid URL.'), *args, **kwargs) 
     504        super(URLField, self).__init__(url_re, max_length, min_length, *args, 
     505                                       **kwargs) 
    500506        self.verify_exists = verify_exists 
    501507        self.user_agent = validator_user_agent 
     
    522528                u = urllib2.urlopen(req) 
    523529            except ValueError: 
    524                 raise ValidationError(ugettext(u'Enter a valid URL.')
     530                raise ValidationError(self.error_messages['invalid']
    525531            except: # urllib2.URLError, httplib.InvalidURL, etc. 
    526                 raise ValidationError(ugettext(u'This URL appears to be a broken link.')
     532                raise ValidationError(self.error_messages['invalid_link']
    527533        return value 
    528534 
     
    584590        valid_values = set([smart_unicode(k) for k, v in self.choices]) 
    585591        if value not in valid_values: 
    586             raise ValidationError(ugettext(u'Select a valid choice. That choice is not one of the available choices.')
     592            raise ValidationError(self.error_messages['invalid_choice'] % {'value': value}
    587593        return value 
    588594 
     
    600606        """ 
    601607        if self.required and not value: 
    602             raise ValidationError(ugettext(u'This field is required.')
     608            raise ValidationError(self.error_messages['required']
    603609        elif not self.required and not value: 
    604610            return [] 
    605611        if not isinstance(value, (list, tuple)): 
    606             raise ValidationError(ugettext(u'Enter a list of values.')
     612            raise ValidationError(self.error_messages['invalid_list']
    607613        new_value = [smart_unicode(val) for val in value] 
    608614        # Validate that each value in the value list is in self.choices. 
     
    610616        for val in new_value: 
    611617            if val not in valid_values: 
    612                 raise ValidationError(ugettext(u'Select a valid choice. %s is not one of the available choices.') % val
     618                raise ValidationError(self.error_messages['invalid_choice'] % {'value': val}
    613619        return new_value 
    614620 
     
    680686            if not value or not [v for v in value if v not in EMPTY_VALUES]: 
    681687                if self.required: 
    682                     raise ValidationError(ugettext(u'This field is required.')
     688                    raise ValidationError(self.error_messages['required']
    683689                else: 
    684690                    return self.compress([]) 
    685691        else: 
    686             raise ValidationError(ugettext(u'Enter a list of values.')
     692            raise ValidationError(self.error_messages['invalid']
    687693        for i, field in enumerate(self.fields): 
    688694            try: 
     
    691697                field_value = None 
    692698            if self.required and field_value in EMPTY_VALUES: 
    693                 raise ValidationError(ugettext(u'This field is required.')
     699                raise ValidationError(self.error_messages['required']
    694700            try: 
    695701                clean_data.append(field.clean(field_value)) 
     
    721727 
    722728    def __init__(self, *args, **kwargs): 
    723         fields = (DateField(), TimeField()) 
     729        errors = self.default_error_messages.copy() 
     730        if 'error_messages' in kwargs: 
     731            errors.update(kwargs['error_messages']) 
     732        fields = ( 
     733            DateField(error_messages={'invalid': errors['invalid_date']}), 
     734            TimeField(error_messages={'invalid': errors['invalid_time']}), 
     735        ) 
    724736        super(SplitDateTimeField, self).__init__(fields, *args, **kwargs) 
    725737 
     
    729741            # (possible if SplitDateTimeField has required=False). 
    730742            if data_list[0] in EMPTY_VALUES: 
    731                 raise ValidationError(ugettext(u'Enter a valid date.')
     743                raise ValidationError(self.error_messages['invalid_date']
    732744            if data_list[1] in EMPTY_VALUES: 
    733                 raise ValidationError(ugettext(u'Enter a valid time.')
     745                raise ValidationError(self.error_messages['invalid_time']
    734746            return datetime.datetime.combine(*data_list) 
    735747        return None 
     
    743755 
    744756    def __init__(self, *args, **kwargs): 
    745         RegexField.__init__(self, ipv4_re, 
    746                             error_message=ugettext(u'Enter a valid IPv4 address.'), 
    747                             *args, **kwargs) 
    748  
     757        super(IPAddressField, self).__init__(ipv4_re, *args, **kwargs) 
  • django/branches/queryset-refactor/django/newforms/util.py

    r6690 r6693  
    4747        return u'\n'.join([u'* %s' % force_unicode(e) for e in self]) 
    4848 
     49    def __repr__(self): 
     50        return repr([force_unicode(e) for e in self]) 
     51 
    4952class ValidationError(Exception): 
    5053    def __init__(self, message): 
    51         "ValidationError can be passed a string or a list." 
     54        """ 
     55        ValidationError can be passed any object that can be printed (usually 
     56        a string) or a list of objects. 
     57        """ 
    5258        if isinstance(message, list): 
    5359            self.messages = ErrorList([smart_unicode(msg) for msg in message]) 
    5460        else: 
    55             assert isinstance(message, (basestring, Promise)), ("%s should be a basestring or lazy translation" % repr(message)) 
    5661            message = smart_unicode(message) 
    5762            self.messages = ErrorList([message]) 
     
    6368        # See http://www.python.org/doc/current/tut/node10.html#handling 
    6469        return repr(self.messages) 
    65  
  • django/branches/queryset-refactor/django/test/testcases.py

    r6690 r6693  
    151151                                        " error '%s' (actual errors: %s)" % 
    152152                                            (field, form, i, err, 
    153                                              list(field_errors))) 
     153                                             repr(field_errors))) 
    154154                    elif field in context[form].fields: 
    155155                        self.fail("The field '%s' on form '%s' in context %d" 
  • django/branches/queryset-refactor/docs/newforms.txt

    r6597 r6693  
    10791079    <p>Cc myself: <input type="checkbox" name="cc_myself" /></p> 
    10801080 
     1081``error_messages`` 
     1082~~~~~~~~~~~~~~~~~~ 
     1083 
     1084**New in Django development version** 
     1085 
     1086The ``error_messages`` argument lets you override the default messages which the 
     1087field will raise. Pass in a dictionary with keys matching the error messages you 
     1088want to override. For example:: 
     1089 
     1090    >>> generic = forms.CharField() 
     1091    >>> generic.clean('') 
     1092    Traceback (most recent call last): 
     1093      ... 
     1094    ValidationError: [u'This field is required.'] 
     1095 
     1096    >>> name = forms.CharField(error_messages={'required': 'Please enter your name'}) 
     1097    >>> name.clean('') 
     1098    Traceback (most recent call last): 
     1099      ... 
     1100    ValidationError: [u'Please enter your name'] 
     1101 
     1102In the `built-in Field classes`_ section below, each Field defines the error 
     1103message keys it uses.   
     1104 
    10811105Dynamic initial values 
    10821106---------------------- 
     
    11441168    * Validates that the check box is checked (i.e. the value is ``True``) if 
    11451169      the field has ``required=True``. 
     1170    * Error message keys: ``required`` 
    11461171 
    11471172**New in Django development version:** The empty value for a ``CheckboxInput`` 
     
    11631188    * Validates ``max_length`` or ``min_length``, if they are provided. 
    11641189      Otherwise, all inputs are valid. 
     1190    * Error message keys: ``required``, ``max_length``, ``min_length`` 
    11651191 
    11661192Has two optional arguments for validation, ``max_length`` and ``min_length``. 
     
    11751201    * Normalizes to: A Unicode object. 
    11761202    * Validates that the given value exists in the list of choices. 
     1203    * Error message keys: ``required``, ``invalid_choice`` 
    11771204 
    11781205Takes one extra argument, ``choices``, which is an iterable (e.g., a list or 
     
    11871214    * Validates that the given value is either a ``datetime.date``, 
    11881215      ``datetime.datetime`` or string formatted in a particular date format. 
     1216    * Error message keys: ``required``, ``invalid`` 
    11891217 
    11901218Takes one optional argument, ``input_formats``, which is a list of formats used 
     
    12071235    * Validates that the given value is either a ``datetime.datetime``, 
    12081236      ``datetime.date`` or string formatted in a particular datetime format. 
     1237    * Error message keys: ``required``, ``invalid`` 
    12091238 
    12101239Takes one optional argument, ``input_formats``, which is a list of formats used 
     
    12361265    * Validates that the given value is a decimal. Leading and trailing 
    12371266      whitespace is ignored. 
     1267    * Error message keys: ``required``, ``invalid``, ``max_value``, 
     1268      ``min_value``, ``max_digits``, ``max_decimal_places``, 
     1269      ``max_whole_digits`` 
    12381270 
    12391271Takes four optional arguments: ``max_value``, ``min_value``, ``max_digits``, 
     
    12521284    * Validates that the given value is a valid e-mail address, using a 
    12531285      moderately complex regular expression. 
     1286    * Error message keys: ``required``, ``invalid`` 
    12541287 
    12551288Has two optional arguments for validation, ``max_length`` and ``min_length``. 
     
    12671300      and file name into a single object. 
    12681301    * Validates that non-empty file data has been bound to the form. 
     1302    * Error message keys: ``required``, ``invalid``, ``missing``, ``empty`` 
    12691303 
    12701304An ``UploadedFile`` object has two attributes: 
     
    12971331    * Validates that file data has been bound to the form, and that the 
    12981332      file is of an image format understood by PIL. 
     1333    * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``, 
     1334      ``invalid_image`` 
    12991335 
    13001336Using an ImageField requires that the `Python Imaging Library`_ is installed. 
     
    13131349    * Validates that the given value is an integer. Leading and trailing 
    13141350      whitespace is allowed, as in Python's ``int()`` function. 
     1351    * Error message keys: ``required``, ``invalid``, ``max_value``, 
     1352      ``min_value`` 
    13151353 
    13161354Takes two optional arguments for validation, ``max_value`` and ``min_value``. 
     
    13251363    * Validates that the given value is a valid IPv4 address, using a regular 
    13261364      expression. 
     1365    * Error message keys: ``required``, ``invalid`` 
    13271366 
    13281367``MultipleChoiceField`` 
     
    13341373    * Validates that every value in the given list of values exists in the list 
    13351374      of choices. 
     1375    * Error message keys: ``required``, ``invalid_choice``, ``invalid_list`` 
    13361376 
    13371377Takes one extra argument, ``choices``, which is an iterable (e.g., a list or 
     
    13541394    * Validates that the given value matches against a certain regular 
    13551395      expression. 
     1396    * Error message keys: ``required``, ``invalid`` 
    13561397 
    13571398Takes one required argument, ``regex``, which is a regular expression specified 
     
    13651406    ``max_length``          Ensures the string has at most this many characters. 
    13661407    ``min_length``          Ensures the string has at least this many characters. 
    1367     ``error_message``       Error message to return for failed validation. If no 
    1368                             message is provided, a generic error message will be 
    1369                             used. 
    13701408    ======================  ===================================================== 
     1409 
     1410The optional argument ``error_message`` is also accepted for backwards 
     1411compatibility. The preferred way to provide an error message is to use the 
     1412``error_messages`` argument, passing a dictionary with ``'invalid'`` as a key 
     1413and the error message as the value.  
    13711414 
    13721415``TimeField`` 
     
    13781421    * Validates that the given value is either a ``datetime.time`` or string 
    13791422      formatted in a particular time format. 
     1423    * Error message keys: ``required``, ``invalid`` 
    13801424 
    13811425Takes one optional argument, ``input_formats``, which is a list of formats used 
     
    13941438    * Normalizes to: A Unicode object. 
    13951439    * Validates that the given value is a valid URL. 
     1440    * Error message keys: ``required``, ``invalid``, ``invalid_link`` 
    13961441 
    13971442Takes the following optional arguments: