Ticket #6302: pass_initial_through_with_tests_2.diff

File pass_initial_through_with_tests_2.diff, 41.2 KB (added by Brian Rosner, 17 years ago)

this might be overkill, but initial data is now passed to field.clean. should FileField be special cased?

  • django/contrib/localflavor/ar/forms.py

    diff --git a/django/contrib/localflavor/ar/forms.py b/django/contrib/localflavor/ar/forms.py
    index 6374a48..a348a35 100644
    a b class ARPostalCodeField(RegexField):  
    3232        super(ARPostalCodeField, self).__init__(r'^\d{4}$|^[A-HJ-NP-Za-hj-np-z]\d{4}\D{3}$',
    3333            min_length=4, max_length=8, *args, **kwargs)
    3434
    35     def clean(self, value):
    36         value = super(ARPostalCodeField, self).clean(value)
     35    def clean(self, value, initial=None):
     36        value = super(ARPostalCodeField, self).clean(value, initial)
    3737        if value in EMPTY_VALUES:
    3838            return u''
    3939        if len(value) not in (4, 8):
    class ARDNIField(CharField):  
    5555        super(ARDNIField, self).__init__(max_length=10, min_length=7, *args,
    5656                **kwargs)
    5757
    58     def clean(self, value):
     58    def clean(self, value, initial=None):
    5959        """
    6060        Value can be a string either in the [X]X.XXX.XXX or [X]XXXXXXX formats.
    6161        """
    62         value = super(ARDNIField, self).clean(value)
     62        value = super(ARDNIField, self).clean(value, initial)
    6363        if value in EMPTY_VALUES:
    6464            return u''
    6565        if not value.isdigit():
    class ARCUITField(RegexField):  
    8585        super(ARCUITField, self).__init__(r'^\d{2}-?\d{8}-?\d$',
    8686            *args, **kwargs)
    8787
    88     def clean(self, value):
     88    def clean(self, value, initial=None):
    8989        """
    9090        Value can be either a string in the format XX-XXXXXXXX-X or an
    9191        11-digit number.
    9292        """
    93         value = super(ARCUITField, self).clean(value)
     93        value = super(ARCUITField, self).clean(value, initial)
    9494        if value in EMPTY_VALUES:
    9595            return u''
    9696        value, cd = self._canon(value)
  • django/contrib/localflavor/au/forms.py

    diff --git a/django/contrib/localflavor/au/forms.py b/django/contrib/localflavor/au/forms.py
    index ada27b6..ed3665c 100644
    a b class AUPhoneNumberField(Field):  
    2626        'invalid': u'Phone numbers must contain 10 digits.',
    2727    }
    2828
    29     def clean(self, value):
     29    def clean(self, value, initial=None):
    3030        """
    3131        Validate a phone number. Strips parentheses, whitespace and hyphens.
    3232        """
    33         super(AUPhoneNumberField, self).clean(value)
     33        super(AUPhoneNumberField, self).clean(value, initial)
    3434        if value in EMPTY_VALUES:
    3535            return u''
    3636        value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value))
  • django/contrib/localflavor/br/forms.py

    diff --git a/django/contrib/localflavor/br/forms.py b/django/contrib/localflavor/br/forms.py
    index aa7e3b2..32a6dd2 100644
    a b class BRPhoneNumberField(Field):  
    3030        'invalid': _('Phone numbers must be in XX-XXXX-XXXX format.'),
    3131    }
    3232
    33     def clean(self, value):
    34         super(BRPhoneNumberField, self).clean(value)
     33    def clean(self, value, initial=None):
     34        super(BRPhoneNumberField, self).clean(value, initial)
    3535        if value in EMPTY_VALUES:
    3636            return u''
    3737        value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
    class BRStateChoiceField(Field):  
    6565        from br_states import STATE_CHOICES
    6666        self.widget.choices = STATE_CHOICES
    6767
    68     def clean(self, value):
    69         value = super(BRStateChoiceField, self).clean(value)
     68    def clean(self, value, initial=None):
     69        value = super(BRStateChoiceField, self).clean(value, initial)
    7070        if value in EMPTY_VALUES:
    7171            value = u''
    7272        value = smart_unicode(value)
    class BRCPFField(CharField):  
    9999    def __init__(self, *args, **kwargs):
    100100        super(BRCPFField, self).__init__(max_length=14, min_length=11, *args, **kwargs)
    101101
    102     def clean(self, value):
     102    def clean(self, value, initial=None):
    103103        """
    104104        Value can be either a string in the format XXX.XXX.XXX-XX or an
    105105        11-digit number.
    106106        """
    107         value = super(BRCPFField, self).clean(value)
     107        value = super(BRCPFField, self).clean(value, initial)
    108108        if value in EMPTY_VALUES:
    109109            return u''
    110110        orig_value = value[:]
    class BRCNPJField(Field):  
    136136        'max_digits': _("This field requires at least 14 digits"),
    137137    }
    138138
    139     def clean(self, value):
     139    def clean(self, value, initial=None):
    140140        """
    141141        Value can be either a string in the format XX.XXX.XXX/XXXX-XX or a
    142142        group of 14 characters.
    143143        """
    144         value = super(BRCNPJField, self).clean(value)
     144        value = super(BRCNPJField, self).clean(value, initial)
    145145        if value in EMPTY_VALUES:
    146146            return u''
    147147        orig_value = value[:]
  • django/contrib/localflavor/ca/forms.py

    diff --git a/django/contrib/localflavor/ca/forms.py b/django/contrib/localflavor/ca/forms.py
    index b40dba8..fb9e986 100644
    a b class CAPhoneNumberField(Field):  
    2727        'invalid': u'Phone numbers must be in XXX-XXX-XXXX format.',
    2828    }
    2929
    30     def clean(self, value):
     30    def clean(self, value, initial=None):
    3131        """Validate a phone number.
    3232        """
    33         super(CAPhoneNumberField, self).clean(value)
     33        super(CAPhoneNumberField, self).clean(value, initial)
    3434        if value in EMPTY_VALUES:
    3535            return u''
    3636        value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
    class CAProvinceField(Field):  
    4949        'invalid': u'Enter a Canadian province or territory.',
    5050    }
    5151
    52     def clean(self, value):
     52    def clean(self, value, initial=None):
    5353        from ca_provinces import PROVINCES_NORMALIZED
    54         super(CAProvinceField, self).clean(value)
     54        super(CAProvinceField, self).clean(value, initial)
    5555        if value in EMPTY_VALUES:
    5656            return u''
    5757        try:
    class CASocialInsuranceNumberField(Field):  
    8888        'invalid': ugettext('Enter a valid Canadian Social Insurance number in XXX-XXX-XXX format.'),
    8989    }
    9090
    91     def clean(self, value):
    92         super(CASocialInsuranceNumberField, self).clean(value)
     91    def clean(self, value, initial=None):
     92        super(CASocialInsuranceNumberField, self).clean(value, initial)
    9393        if value in EMPTY_VALUES:
    9494            return u''
    9595
  • django/contrib/localflavor/ch/forms.py

    diff --git a/django/contrib/localflavor/ch/forms.py b/django/contrib/localflavor/ch/forms.py
    index 2158fba..884392b 100644
    a b class CHPhoneNumberField(Field):  
    3131        'invalid': 'Phone numbers must be in 0XX XXX XX XX format.',
    3232    }
    3333
    34     def clean(self, value):
    35         super(CHPhoneNumberField, self).clean(value)
     34    def clean(self, value, initial=None):
     35        super(CHPhoneNumberField, self).clean(value, initial)
    3636        if value in EMPTY_VALUES:
    3737            return u''
    3838        value = re.sub('(\.|\s|/|-)', '', smart_unicode(value))
    class CHIdentityCardNumberField(Field):  
    9595
    9696        return str(calculated_checksum)[-1] == given_checksum
    9797
    98     def clean(self, value):
    99         super(CHIdentityCardNumberField, self).clean(value)
     98    def clean(self, value, initial=None):
     99        super(CHIdentityCardNumberField, self).clean(value, initial)
    100100        if value in EMPTY_VALUES:
    101101            return u''
    102102
  • django/contrib/localflavor/cl/forms.py

    diff --git a/django/contrib/localflavor/cl/forms.py b/django/contrib/localflavor/cl/forms.py
    index 2f5ac29..89f4daa 100644
    a b class CLRutField(RegexField):  
    4141            # the real world.
    4242            super(CLRutField, self).__init__(r'^[\d\.]{1,11}-?[\dkK]$', *args, **kwargs)
    4343
    44     def clean(self, value):
     44    def clean(self, value, initial=None):
    4545        """
    4646        Check and clean the Chilean RUT.
    4747        """
    48         super(CLRutField, self).clean(value)
     48        super(CLRutField, self).clean(value, initial)
    4949        if value in EMPTY_VALUES:
    5050            return u''
    5151        rut, verificador = self._canonify(value)
  • django/contrib/localflavor/de/forms.py

    diff --git a/django/contrib/localflavor/de/forms.py b/django/contrib/localflavor/de/forms.py
    index 76ce215..0658d25 100644
    a b class DEIdentityCardNumberField(Field):  
    6060
    6161        return str(calculated_checksum)[-1] == given_checksum
    6262
    63     def clean(self, value):
    64         super(DEIdentityCardNumberField, self).clean(value)
     63    def clean(self, value, initial=None):
     64        super(DEIdentityCardNumberField, self).clean(value, initial)
    6565        if value in EMPTY_VALUES:
    6666            return u''
    6767        match = re.match(id_re, value)
  • django/contrib/localflavor/es/forms.py

    diff --git a/django/contrib/localflavor/es/forms.py b/django/contrib/localflavor/es/forms.py
    index 81186f8..aeb96de 100644
    a b class ESIdentityCardNumberField(RegexField):  
    8181                error_message=self.default_error_messages['invalid%s' % (self.only_nif and '_only_nif' or '')],
    8282                *args, **kwargs)
    8383
    84     def clean(self, value):
    85         super(ESIdentityCardNumberField, self).clean(value)
     84    def clean(self, value, initial=None):
     85        super(ESIdentityCardNumberField, self).clean(value, initial)
    8686        if value in EMPTY_VALUES:
    8787            return u''
    8888        nif_get_checksum = lambda d: self.nif_control[int(d)%23]
    class ESCCCField(RegexField):  
    147147        super(ESCCCField, self).__init__(r'^\d{4}[ -]?\d{4}[ -]?\d{2}[ -]?\d{10}$',
    148148            max_length=None, min_length=None, *args, **kwargs)
    149149
    150     def clean(self, value):
    151         super(ESCCCField, self).clean(value)
     150    def clean(self, value, initial=None):
     151        super(ESCCCField, self).clean(value, initial)
    152152        if value in EMPTY_VALUES:
    153153            return u''
    154154        control_str = [1, 2, 4, 8, 5, 10, 9, 7, 3, 6]
  • django/contrib/localflavor/fi/forms.py

    diff --git a/django/contrib/localflavor/fi/forms.py b/django/contrib/localflavor/fi/forms.py
    index a0274da..4c0c57a 100644
    a b class FISocialSecurityNumber(Field):  
    2828        'invalid': ugettext('Enter a valid Finnish social security number.'),
    2929    }
    3030
    31     def clean(self, value):
    32         super(FISocialSecurityNumber, self).clean(value)
     31    def clean(self, value, initial=None):
     32        super(FISocialSecurityNumber, self).clean(value, initial)
    3333        if value in EMPTY_VALUES:
    3434            return u''
    3535
  • django/contrib/localflavor/fr/forms.py

    diff --git a/django/contrib/localflavor/fr/forms.py b/django/contrib/localflavor/fr/forms.py
    index 635b62e..7408deb 100644
    a b class FRPhoneNumberField(Field):  
    3030        'invalid': u'Phone numbers must be in 0X XX XX XX XX format.',
    3131    }
    3232
    33     def clean(self, value):
    34         super(FRPhoneNumberField, self).clean(value)
     33    def clean(self, value, initial=None):
     34        super(FRPhoneNumberField, self).clean(value, initial)
    3535        if value in EMPTY_VALUES:
    3636            return u''
    3737        value = re.sub('(\.|\s)', '', smart_unicode(value))
  • django/contrib/localflavor/in_/forms.py

    diff --git a/django/contrib/localflavor/in_/forms.py b/django/contrib/localflavor/in_/forms.py
    index 1cb303d..c323366 100644
    a b class INStateField(Field):  
    2828        'invalid': u'Enter a Indian state or territory.',
    2929    }
    3030
    31     def clean(self, value):
     31    def clean(self, value, initial=None):
    3232        from in_states import STATES_NORMALIZED
    33         super(INStateField, self).clean(value)
     33        super(INStateField, self).clean(value, initial)
    3434        if value in EMPTY_VALUES:
    3535            return u''
    3636        try:
  • django/contrib/localflavor/is_/forms.py

    diff --git a/django/contrib/localflavor/is_/forms.py b/django/contrib/localflavor/is_/forms.py
    index ea7a1e0..e7bba15 100644
    a b class ISIdNumberField(RegexField):  
    2222        kwargs['min_length'],kwargs['max_length'] = 10,11
    2323        super(ISIdNumberField, self).__init__(r'^\d{6}(-| )?\d{4}$', *args, **kwargs)
    2424
    25     def clean(self, value):
    26         value = super(ISIdNumberField, self).clean(value)
     25    def clean(self, value, initial=None):
     26        value = super(ISIdNumberField, self).clean(value, initial)
    2727
    2828        if value in EMPTY_VALUES:
    2929            return u''
    class ISPhoneNumberField(RegexField):  
    6464        kwargs['min_length'], kwargs['max_length'] = 7,8
    6565        super(ISPhoneNumberField, self).__init__(r'^\d{3}(-| )?\d{4}$', *args, **kwargs)
    6666
    67     def clean(self, value):
    68         value = super(ISPhoneNumberField, self).clean(value)
     67    def clean(self, value, initial=None):
     68        value = super(ISPhoneNumberField, self).clean(value, initial)
    6969
    7070        if value in EMPTY_VALUES:
    7171            return u''
  • django/contrib/localflavor/it/forms.py

    diff --git a/django/contrib/localflavor/it/forms.py b/django/contrib/localflavor/it/forms.py
    index 88e6573..6d53780 100644
    a b class ITSocialSecurityNumberField(RegexField):  
    4747        super(ITSocialSecurityNumberField, self).__init__(r'^\w{3}\s*\w{3}\s*\w{5}\s*\w{5}$',
    4848        max_length=None, min_length=None, *args, **kwargs)
    4949
    50     def clean(self, value):
    51         value = super(ITSocialSecurityNumberField, self).clean(value)
     50    def clean(self, value, initial=None):
     51        value = super(ITSocialSecurityNumberField, self).clean(value, initial)
    5252        if value == u'':
    5353            return value
    5454        value = re.sub('\s', u'', value).upper()
    class ITVatNumberField(Field):  
    6868        'invalid': ugettext(u'Enter a valid VAT number.'),
    6969    }
    7070
    71     def clean(self, value):
    72         value = super(ITVatNumberField, self).clean(value)
     71    def clean(self, value, initial=None):
     72        value = super(ITVatNumberField, self).clean(value, initial)
    7373        if value == u'':
    7474            return value
    7575        try:
  • django/contrib/localflavor/jp/forms.py

    diff --git a/django/contrib/localflavor/jp/forms.py b/django/contrib/localflavor/jp/forms.py
    index 13083aa..e856260 100644
    a b class JPPostalCodeField(RegexField):  
    2323        super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$',
    2424            max_length=None, min_length=None, *args, **kwargs)
    2525
    26     def clean(self, value):
     26    def clean(self, value, initial=None):
    2727        """
    2828        Validates the input and returns a string that contains only numbers.
    2929        Returns an empty string for empty values.
    3030        """
    31         v = super(JPPostalCodeField, self).clean(value)
     31        v = super(JPPostalCodeField, self).clean(value, initial)
    3232        return v.replace('-', '')
    3333
    3434class JPPrefectureSelect(Select):
  • django/contrib/localflavor/nl/forms.py

    diff --git a/django/contrib/localflavor/nl/forms.py b/django/contrib/localflavor/nl/forms.py
    index 7484849..7bb1a30 100644
    a b class NLZipCodeField(Field):  
    2121        'invalid': _('Enter a valid postal code'),
    2222    }
    2323
    24     def clean(self, value):
    25         super(NLZipCodeField, self).clean(value)
     24    def clean(self, value, initial=None):
     25        super(NLZipCodeField, self).clean(value, initial)
    2626        if value in EMPTY_VALUES:
    2727            return u''
    2828
    class NLPhoneNumberField(Field):  
    5252        'invalid': _('Enter a valid phone number'),
    5353    }
    5454
    55     def clean(self, value):
    56         super(NLPhoneNumberField, self).clean(value)
     55    def clean(self, value, initial=None):
     56        super(NLPhoneNumberField, self).clean(value, initial)
    5757        if value in EMPTY_VALUES:
    5858            return u''
    5959
    class NLSoFiNumberField(Field):  
    7878        'invalid': _('Enter a valid SoFi number'),
    7979    }
    8080
    81     def clean(self, value):
    82         super(NLSoFiNumberField, self).clean(value)
     81    def clean(self, value, initial=None):
     82        super(NLSoFiNumberField, self).clean(value, initial)
    8383        if value in EMPTY_VALUES:
    8484            return u''
    8585
  • django/contrib/localflavor/no/forms.py

    diff --git a/django/contrib/localflavor/no/forms.py b/django/contrib/localflavor/no/forms.py
    index 8dc0019..94e039f 100644
    a b class NOSocialSecurityNumber(Field):  
    3333        'invalid': ugettext(u'Enter a valid Norwegian social security number.'),
    3434    }
    3535
    36     def clean(self, value):
    37         super(NOSocialSecurityNumber, self).clean(value)
     36    def clean(self, value, initial=None):
     37        super(NOSocialSecurityNumber, self).clean(value, initial)
    3838        if value in EMPTY_VALUES:
    3939            return u''
    4040
  • django/contrib/localflavor/pe/forms.py

    diff --git a/django/contrib/localflavor/pe/forms.py b/django/contrib/localflavor/pe/forms.py
    index 57c9d44..4b86eee 100644
    a b class PEDNIField(CharField):  
    2828        super(PEDNIField, self).__init__(max_length=8, min_length=8, *args,
    2929                **kwargs)
    3030
    31     def clean(self, value):
     31    def clean(self, value, initial=None):
    3232        """
    3333        Value must be a string in the XXXXXXXX formats.
    3434        """
    35         value = super(PEDNIField, self).clean(value)
     35        value = super(PEDNIField, self).clean(value, initial)
    3636        if value in EMPTY_VALUES:
    3737            return u''
    3838        if not value.isdigit():
    class PERUCField(RegexField):  
    5656        super(PERUCField, self).__init__(max_length=11, min_length=11, *args,
    5757            **kwargs)
    5858
    59     def clean(self, value):
     59    def clean(self, value, initial=None):
    6060        """
    6161        Value must be an 11-digit number.
    6262        """
    63         value = super(PERUCField, self).clean(value)
     63        value = super(PERUCField, self).clean(value, initial)
    6464        if value in EMPTY_VALUES:
    6565            return u''
    6666        if not value.isdigit():
  • django/contrib/localflavor/pl/forms.py

    diff --git a/django/contrib/localflavor/pl/forms.py b/django/contrib/localflavor/pl/forms.py
    index b02dad7..3b0d9c3 100644
    a b class PLNationalIdentificationNumberField(RegexField):  
    4444        super(PLNationalIdentificationNumberField, self).__init__(r'^\d{11}$',
    4545            max_length=None, min_length=None, *args, **kwargs)
    4646
    47     def clean(self,value):
    48         super(PLNationalIdentificationNumberField, self).clean(value)
     47    def clean(self, value, initial=None):
     48        super(PLNationalIdentificationNumberField, self).clean(value, initial)
    4949        if not self.has_valid_checksum(value):
    5050            raise ValidationError(self.error_messages['checksum'])
    5151        return u'%s' % value
    class PLTaxNumberField(RegexField):  
    7777        super(PLTaxNumberField, self).__init__(r'^\d{3}-\d{3}-\d{2}-\d{2}$|^\d{2}-\d{2}-\d{3}-\d{3}$',
    7878            max_length=None, min_length=None, *args, **kwargs)
    7979
    80     def clean(self,value):
    81         super(PLTaxNumberField, self).clean(value)
     80    def clean(self, value, initial=None):
     81        super(PLTaxNumberField, self).clean(value, initial)
    8282        value = re.sub("[-]", "", value)
    8383        if not self.has_valid_checksum(value):
    8484            raise ValidationError(self.error_messages['checksum'])
    class PLNationalBusinessRegisterField(RegexField):  
    117117        super(PLNationalBusinessRegisterField, self).__init__(r'^\d{7,9}$',
    118118            max_length=None, min_length=None, *args, **kwargs)
    119119
    120     def clean(self,value):
    121         super(PLNationalBusinessRegisterField, self).clean(value)
     120    def clean(self, value, initial=None):
     121        super(PLNationalBusinessRegisterField, self).clean(value, initial)
    122122        if not self.has_valid_checksum(value):
    123123            raise ValidationError(self.error_messages['checksum'])
    124124        return u'%s' % value
  • django/contrib/localflavor/sk/forms.py

    diff --git a/django/contrib/localflavor/sk/forms.py b/django/contrib/localflavor/sk/forms.py
    index 711d70f..127238d 100644
    a b class SKPostalCodeField(RegexField):  
    3434        super(SKPostalCodeField, self).__init__(r'^\d{5}$|^\d{3} \d{2}$',
    3535            max_length=None, min_length=None, *args, **kwargs)
    3636
    37     def clean(self, value):
     37    def clean(self, value, initial=None):
    3838        """
    3939        Validates the input and returns a string that contains only numbers.
    4040        Returns an empty string for empty values.
    4141        """
    42         v = super(SKPostalCodeField, self).clean(value)
     42        v = super(SKPostalCodeField, self).clean(value, initial)
    4343        return v.replace(' ', '')
  • django/contrib/localflavor/uk/forms.py

    diff --git a/django/contrib/localflavor/uk/forms.py b/django/contrib/localflavor/uk/forms.py
    index 52cd7ad..603e5bd 100644
    a b class UKPostcodeField(CharField):  
    2525    postcode_regex = re.compile(r'^(GIR 0AA|%s %s)$' % (outcode_pattern, incode_pattern))
    2626    space_regex = re.compile(r' *(%s)$' % incode_pattern)
    2727
    28     def clean(self, value):
    29         value = super(UKPostcodeField, self).clean(value)
     28    def clean(self, value, initial=None):
     29        value = super(UKPostcodeField, self).clean(value, initial)
    3030        if value == u'':
    3131            return value
    3232        postcode = value.upper().strip()
  • django/contrib/localflavor/us/forms.py

    diff --git a/django/contrib/localflavor/us/forms.py b/django/contrib/localflavor/us/forms.py
    index d6aa684..721f819 100644
    a b class USPhoneNumberField(Field):  
    2525        'invalid': u'Phone numbers must be in XXX-XXX-XXXX format.',
    2626    }
    2727
    28     def clean(self, value):
    29         super(USPhoneNumberField, self).clean(value)
     28    def clean(self, value, initial=None):
     29        super(USPhoneNumberField, self).clean(value, initial)
    3030        if value in EMPTY_VALUES:
    3131            return u''
    3232        value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
    class USSocialSecurityNumberField(Field):  
    5454        'invalid': ugettext('Enter a valid U.S. Social Security number in XXX-XX-XXXX format.'),
    5555    }
    5656
    57     def clean(self, value):
    58         super(USSocialSecurityNumberField, self).clean(value)
     57    def clean(self, value, initial=None):
     58        super(USSocialSecurityNumberField, self).clean(value, initial)
    5959        if value in EMPTY_VALUES:
    6060            return u''
    6161        match = re.match(ssn_re, value)
    class USStateField(Field):  
    8787        'invalid': u'Enter a U.S. state or territory.',
    8888    }
    8989
    90     def clean(self, value):
     90    def clean(self, value, initial=None):
    9191        from us_states import STATES_NORMALIZED
    92         super(USStateField, self).clean(value)
     92        super(USStateField, self).clean(value, initial)
    9393        if value in EMPTY_VALUES:
    9494            return u''
    9595        try:
  • django/contrib/localflavor/za/forms.py

    diff --git a/django/contrib/localflavor/za/forms.py b/django/contrib/localflavor/za/forms.py
    index b3613b5..f01c9c3 100644
    a b class ZAIDField(Field):  
    2020        'invalid': _(u'Enter a valid South African ID number'),
    2121    }
    2222
    23     def clean(self, value):
     23    def clean(self, value, initial=None):
    2424        # strip spaces and dashes
    2525        value = value.strip().replace(' ', '').replace('-', '')
    2626
    27         super(ZAIDField, self).clean(value)
     27        super(ZAIDField, self).clean(value, initial)
    2828
    2929        if value in EMPTY_VALUES:
    3030            return u''
  • django/db/models/fields/__init__.py

    diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
    index 139a096..7bc6c58 100644
    a b class FileField(Field):  
    797797        return os.path.normpath(f)
    798798
    799799    def save_form_data(self, instance, data):
    800         if data:
     800        from django.newforms.fields import UploadedFile
     801        if data and isinstance(data, UploadedFile):
    801802            getattr(instance, "save_%s_file" % self.name)(data.filename, data.content, save=False)
    802803
    803804    def formfield(self, **kwargs):
    804805        defaults = {'form_class': forms.FileField}
    805         # If a file has been provided previously, then the form doesn't require
    806         # that a new file is provided this time.
    807         if 'initial' in kwargs:
    808             defaults['required'] = False
    809806        defaults.update(kwargs)
    810807        return super(FileField, self).formfield(**defaults)
    811808
  • django/newforms/fields.py

    diff --git a/django/newforms/fields.py b/django/newforms/fields.py
    index 3b8f419..29f565c 100644
    a b class Field(object):  
    9393        messages.update(error_messages or {})
    9494        self.error_messages = messages
    9595
    96     def clean(self, value):
     96    def clean(self, value, initial=None):
    9797        """
    9898        Validates the given value and returns its "cleaned" value as an
    9999        appropriate Python object.
    class CharField(Field):  
    128128        self.max_length, self.min_length = max_length, min_length
    129129        super(CharField, self).__init__(*args, **kwargs)
    130130
    131     def clean(self, value):
     131    def clean(self, value, initial=None):
    132132        "Validates max_length and min_length. Returns a Unicode object."
    133         super(CharField, self).clean(value)
     133        super(CharField, self).clean(value, initial)
    134134        if value in EMPTY_VALUES:
    135135            return u''
    136136        value = smart_unicode(value)
    class IntegerField(Field):  
    157157        self.max_value, self.min_value = max_value, min_value
    158158        super(IntegerField, self).__init__(*args, **kwargs)
    159159
    160     def clean(self, value):
     160    def clean(self, value, initial=None):
    161161        """
    162162        Validates that int() can be called on the input. Returns the result
    163163        of int(). Returns None for empty values.
    164164        """
    165         super(IntegerField, self).clean(value)
     165        super(IntegerField, self).clean(value, initial)
    166166        if value in EMPTY_VALUES:
    167167            return None
    168168        try:
    class FloatField(Field):  
    186186        self.max_value, self.min_value = max_value, min_value
    187187        Field.__init__(self, *args, **kwargs)
    188188
    189     def clean(self, value):
     189    def clean(self, value, initial=None):
    190190        """
    191191        Validates that float() can be called on the input. Returns a float.
    192192        Returns None for empty values.
    193193        """
    194         super(FloatField, self).clean(value)
     194        super(FloatField, self).clean(value, initial)
    195195        if not self.required and value in EMPTY_VALUES:
    196196            return None
    197197        try:
    class DecimalField(Field):  
    219219        self.max_digits, self.decimal_places = max_digits, decimal_places
    220220        Field.__init__(self, *args, **kwargs)
    221221
    222     def clean(self, value):
     222    def clean(self, value, initial=None):
    223223        """
    224224        Validates that the input is a decimal number. Returns a Decimal
    225225        instance. Returns None for empty values. Ensures that there are no more
    226226        than max_digits in the number, and no more than decimal_places digits
    227227        after the decimal point.
    228228        """
    229         super(DecimalField, self).clean(value)
     229        super(DecimalField, self).clean(value, initial)
    230230        if not self.required and value in EMPTY_VALUES:
    231231            return None
    232232        value = smart_str(value).strip()
    class DateField(Field):  
    266266        super(DateField, self).__init__(*args, **kwargs)
    267267        self.input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS
    268268
    269     def clean(self, value):
     269    def clean(self, value, initial=None):
    270270        """
    271271        Validates that the input can be converted to a date. Returns a Python
    272272        datetime.date object.
    273273        """
    274         super(DateField, self).clean(value)
     274        super(DateField, self).clean(value, initial)
    275275        if value in EMPTY_VALUES:
    276276            return None
    277277        if isinstance(value, datetime.datetime):
    class TimeField(Field):  
    299299        super(TimeField, self).__init__(*args, **kwargs)
    300300        self.input_formats = input_formats or DEFAULT_TIME_INPUT_FORMATS
    301301
    302     def clean(self, value):
     302    def clean(self, value, initial=None):
    303303        """
    304304        Validates that the input can be converted to a time. Returns a Python
    305305        datetime.time object.
    306306        """
    307         super(TimeField, self).clean(value)
     307        super(TimeField, self).clean(value, initial)
    308308        if value in EMPTY_VALUES:
    309309            return None
    310310        if isinstance(value, datetime.time):
    class DateTimeField(Field):  
    338338        super(DateTimeField, self).__init__(*args, **kwargs)
    339339        self.input_formats = input_formats or DEFAULT_DATETIME_INPUT_FORMATS
    340340
    341     def clean(self, value):
     341    def clean(self, value, initial=None):
    342342        """
    343343        Validates that the input can be converted to a datetime. Returns a
    344344        Python datetime.datetime object.
    345345        """
    346         super(DateTimeField, self).clean(value)
     346        super(DateTimeField, self).clean(value, initial)
    347347        if value in EMPTY_VALUES:
    348348            return None
    349349        if isinstance(value, datetime.datetime):
    class RegexField(CharField):  
    380380            regex = re.compile(regex)
    381381        self.regex = regex
    382382
    383     def clean(self, value):
     383    def clean(self, value, initial=None):
    384384        """
    385385        Validates that the input matches the regular expression. Returns a
    386386        Unicode object.
    387387        """
    388         value = super(RegexField, self).clean(value)
     388        value = super(RegexField, self).clean(value, initial)
    389389        if value == u'':
    390390            return value
    391391        if not self.regex.search(value):
    class FileField(Field):  
    437437    def __init__(self, *args, **kwargs):
    438438        super(FileField, self).__init__(*args, **kwargs)
    439439
    440     def clean(self, data):
    441         super(FileField, self).clean(data)
     440    def clean(self, data, initial=None):
     441        super(FileField, self).clean(initial or data)
    442442        if not self.required and data in EMPTY_VALUES:
    443443            return None
     444        elif not data and initial:
     445            return initial
    444446        try:
    445447            f = UploadedFile(data['filename'], data['content'])
    446448        except TypeError:
    class ImageField(FileField):  
    456458        'invalid_image': _(u"Upload a valid image. The file you uploaded was either not an image or a corrupted image."),
    457459    }
    458460
    459     def clean(self, data):
     461    def clean(self, data, initial):
    460462        """
    461463        Checks that the file-upload field data contains a valid image (GIF, JPG,
    462464        PNG, possibly others -- whatever the Python Imaging Library supports).
    463465        """
    464         f = super(ImageField, self).clean(data)
     466        f = super(ImageField, self).clean(data, initial)
    465467        if f is None:
    466468            return None
    467469        from PIL import Image
    class URLField(RegexField):  
    500502        self.verify_exists = verify_exists
    501503        self.user_agent = validator_user_agent
    502504
    503     def clean(self, value):
     505    def clean(self, value, initial=None):
    504506        # If no URL scheme given, assume http://
    505507        if value and '://' not in value:
    506508            value = u'http://%s' % value
    507         value = super(URLField, self).clean(value)
     509        value = super(URLField, self).clean(value, initial)
    508510        if value == u'':
    509511            return value
    510512        if self.verify_exists:
    class URLField(RegexField):  
    529531class BooleanField(Field):
    530532    widget = CheckboxInput
    531533
    532     def clean(self, value):
     534    def clean(self, value, initial=None):
    533535        """Returns a Python boolean object."""
    534         super(BooleanField, self).clean(value)
     536        super(BooleanField, self).clean(value, initial)
    535537        # Explicitly check for the string 'False', which is what a hidden field
    536538        # will submit for False. Because bool("True") == True, we don't need to
    537539        # handle that explicitly.
    class NullBooleanField(BooleanField):  
    546548    """
    547549    widget = NullBooleanSelect
    548550
    549     def clean(self, value):
     551    def clean(self, value, initial=None):
    550552        return {True: True, False: False}.get(value, None)
    551553
    552554class ChoiceField(Field):
    class ChoiceField(Field):  
    572574
    573575    choices = property(_get_choices, _set_choices)
    574576
    575     def clean(self, value):
     577    def clean(self, value, initial=None):
    576578        """
    577579        Validates that the input is in self.choices.
    578580        """
    579         value = super(ChoiceField, self).clean(value)
     581        value = super(ChoiceField, self).clean(value, initial)
    580582        if value in EMPTY_VALUES:
    581583            value = u''
    582584        value = smart_unicode(value)
    class MultipleChoiceField(ChoiceField):  
    595597        'invalid_list': _(u'Enter a list of values.'),
    596598    }
    597599
    598     def clean(self, value):
     600    def clean(self, value, initial=None):
    599601        """
    600602        Validates that the input is a list or tuple.
    601603        """
    class ComboField(Field):  
    626628            f.required = False
    627629        self.fields = fields
    628630
    629     def clean(self, value):
     631    def clean(self, value, initial=None):
    630632        """
    631633        Validates the given value against all of self.fields, which is a
    632634        list of Field instances.
    633635        """
    634         super(ComboField, self).clean(value)
     636        super(ComboField, self).clean(value, initial)
    635637        for field in self.fields:
    636             value = field.clean(value)
     638            value = field.clean(value, initial)
    637639        return value
    638640
    639641class MultiValueField(Field):
    class MultiValueField(Field):  
    666668            f.required = False
    667669        self.fields = fields
    668670
    669     def clean(self, value):
     671    def clean(self, value, initial=None):
    670672        """
    671673        Validates every value in the given list. A value is validated against
    672674        the corresponding Field in self.fields.
  • django/newforms/forms.py

    diff --git a/django/newforms/forms.py b/django/newforms/forms.py
    index 556c00a..94232e3 100644
    a b class BaseForm(StrAndUnicode):  
    181181            # Each widget type knows how to retrieve its own data, because some
    182182            # widgets split data over several HTML fields.
    183183            value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
     184            initial = field.widget.value_from_initialdict(self.initial, name)
    184185            try:
    185                 value = field.clean(value)
     186                value = field.clean(value, initial)
    186187                self.cleaned_data[name] = value
    187188                if hasattr(self, 'clean_%s' % name):
    188189                    value = getattr(self, 'clean_%s' % name)()
  • django/newforms/models.py

    diff --git a/django/newforms/models.py b/django/newforms/models.py
    index fd0087a..4c130a3 100644
    a b class ModelChoiceField(ChoiceField):  
    360360
    361361    choices = property(_get_choices, _set_choices)
    362362
    363     def clean(self, value):
     363    def clean(self, value, initial=None):
    364364        Field.clean(self, value)
    365365        if value in EMPTY_VALUES:
    366366            return None
    class ModelMultipleChoiceField(ModelChoiceField):  
    386386            cache_choices, required, widget, label, initial, help_text,
    387387            *args, **kwargs)
    388388
    389     def clean(self, value):
     389    def clean(self, value, initial=None):
    390390        if self.required and not value:
    391391            raise ValidationError(self.error_messages['required'])
    392392        elif not self.required and not value:
  • django/newforms/widgets.py

    diff --git a/django/newforms/widgets.py b/django/newforms/widgets.py
    index 5808348..fd585ed 100644
    a b class Widget(object):  
    7777        return id_
    7878    id_for_label = classmethod(id_for_label)
    7979
     80    def value_from_initialdict(self, initial, name):
     81        """
     82        Given a dictionary of initial data return the value for this widget.
     83        Returns None if it's not provided.
     84        """
     85        if name in initial:
     86            return initial[name]
     87        return None
     88
    8089class Input(Widget):
    8190    """
    8291    Base class for all <input> widgets (except type='checkbox' and
  • docs/newforms.txt

    diff --git a/docs/newforms.txt b/docs/newforms.txt
    index 19f42cb..257945e 100644
    a b keep it simple and assume e-mail validation is contained in a function called  
    15941594    from django import newforms as forms
    15951595
    15961596    class MultiEmailField(forms.Field):
    1597         def clean(self, value):
     1597        def clean(self, value, initial=None):
    15981598            if not value:
    15991599                raise forms.ValidationError('Enter at least one e-mail address.')
    16001600            emails = value.split(',')
  • tests/modeltests/model_forms/models.py

    diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py
    index 17c3b35..ff3f20e 100644
    a b examples are probably a poor fit for the ModelForm syntax. In other words,  
    77most of these tests should be rewritten.
    88"""
    99
     10import os
     11import tempfile
     12
    1013from django.db import models
    1114
    1215ARTICLE_STATUS = (
    class PhoneNumber(models.Model):  
    5558    def __unicode__(self):
    5659        return self.phone
    5760
     61class TextFile(models.Model):
     62    description = models.CharField(max_length=20)
     63    file = models.FileField(upload_to=tempfile.gettempdir())
     64
     65    def __unicode__(self):
     66        return self.description
     67
    5868__test__ = {'API_TESTS': """
    5969>>> from django import newforms as forms
    6070>>> from django.newforms.models import ModelForm
    ValidationError: [u'Select a valid choice. 4 is not one of the available choices  
    701711True
    702712>>> f.cleaned_data
    703713{'phone': u'312-555-1212', 'description': u'Assistance'}
     714
     715# FileField ###################################################################
     716
     717>>> class TextFileForm(ModelForm):
     718...     class Meta:
     719...         model = TextFile
     720
     721Test conditions when files is either not given or empty.
     722
     723>>> f = TextFileForm(data={'description': u'Assistance'})
     724>>> f.is_valid()
     725False
     726>>> f = TextFileForm(data={'description': u'Assistance'}, files={})
     727>>> f.is_valid()
     728False
     729
     730Upload a file and ensure it all works as expected.
     731
     732>>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': {'filename': 'test1.txt', 'content': 'hello world'}})
     733>>> f.is_valid()
     734True
     735>>> type(f.cleaned_data['file'])
     736<class 'django.newforms.fields.UploadedFile'>
     737>>> instance = f.save()
     738>>> instance.file
     739u'.../test1.txt'
     740
     741Edit an instance that already has the file defined in the model. This will not
     742save the file again, but leave it exactly as it is.
     743
     744>>> f = TextFileForm(data={'description': u'Assistance'}, instance=instance)
     745>>> f.is_valid()
     746True
     747>>> f.cleaned_data['file']
     748u'.../test1.txt'
     749>>> instance = f.save()
     750>>> instance.file
     751u'.../test1.txt'
     752
     753Delete the current file since this is not done by Django.
     754
     755>>> os.unlink(instance.get_file_filename())
     756
     757Override the file by uploading a new one.
     758
     759>>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': {'filename': 'test2.txt', 'content': 'hello world'}}, instance=instance)
     760>>> f.is_valid()
     761True
     762>>> instance = f.save()
     763>>> instance.file
     764u'.../test2.txt'
     765
     766>>> instance.delete()
     767
     768Test the non-required FileField
     769
     770>>> f = TextFileForm(data={'description': u'Assistance'})
     771>>> f.fields['file'].required = False
     772>>> f.is_valid()
     773True
     774>>> instance = f.save()
     775>>> instance.file
     776''
     777
     778>>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': {'filename': 'test3.txt', 'content': 'hello world'}}, instance=instance)
     779>>> f.is_valid()
     780True
     781>>> instance = f.save()
     782>>> instance.file
     783u'.../test3.txt'
     784>>> instance.delete()
    704785"""}
  • tests/regressiontests/forms/fields.py

    diff --git a/tests/regressiontests/forms/fields.py b/tests/regressiontests/forms/fields.py
    index cff5db6..9216210 100644
    a b Traceback (most recent call last):  
    749749...
    750750ValidationError: [u'This field is required.']
    751751
     752>>> f.clean('', '')
     753Traceback (most recent call last):
     754...
     755ValidationError: [u'This field is required.']
     756
     757>>> f.clean('', 'files/test1.pdf')
     758'files/test1.pdf'
     759
    752760>>> f.clean(None)
    753761Traceback (most recent call last):
    754762...
    755763ValidationError: [u'This field is required.']
    756764
     765>>> f.clean(None, '')
     766Traceback (most recent call last):
     767...
     768ValidationError: [u'This field is required.']
     769
     770>>> f.clean(None, 'files/test2.pdf')
     771'files/test2.pdf'
     772
    757773>>> f.clean({})
    758774Traceback (most recent call last):
    759775...
    760776ValidationError: [u'No file was submitted.']
    761777
     778>>> f.clean({}, '')
     779Traceback (most recent call last):
     780...
     781ValidationError: [u'No file was submitted.']
     782
     783>>> f.clean({}, 'files/test3.pdf')
     784'files/test3.pdf'
     785
    762786>>> f.clean('some content that is not a file')
    763787Traceback (most recent call last):
    764788...
    765789ValidationError: [u'No file was submitted. Check the encoding type on the form.']
    766790
    767 >>> f.clean({'filename': 'name', 'content':None})
     791>>> f.clean({'filename': 'name', 'content': None})
    768792Traceback (most recent call last):
    769793...
    770794ValidationError: [u'The submitted file is empty.']
    771795
    772 >>> f.clean({'filename': 'name', 'content':''})
     796>>> f.clean({'filename': 'name', 'content': ''})
    773797Traceback (most recent call last):
    774798...
    775799ValidationError: [u'The submitted file is empty.']
    776800
    777 >>> type(f.clean({'filename': 'name', 'content':'Some File Content'}))
     801>>> type(f.clean({'filename': 'name', 'content': 'Some File Content'}))
     802<class 'django.newforms.fields.UploadedFile'>
     803
     804>>> type(f.clean({'filename': 'name', 'content': 'Some File Content'}, 'files/test4.pdf'))
    778805<class 'django.newforms.fields.UploadedFile'>
    779806
    780807# URLField ##################################################################
Back to Top