Ticket #10895: localflavor_br_forms_r10620.diff

File localflavor_br_forms_r10620.diff, 6.3 KB (added by luizvital, 16 years ago)

patch on r10620

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

     
    8686    """
    8787    This field validate a CPF number or a CPF string. A CPF number is
    8888    compounded by XXX.XXX.XXX-VD. The two last digits are check digits.
     89    By default, the cleaned value is in the same format as entered.
     90    If you'd like to keep a unique format for cleaned values use
     91    the parameters "always_return_formatted" set to `True` and
     92    adjust "return_format" to your needs, the default format is '%s.%s.%s-%s'.
    8993
    9094    More information:
    9195    http://en.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas
     
    96100        'digits_only': _("This field requires only numbers."),
    97101    }
    98102
    99     def __init__(self, *args, **kwargs):
    100         super(BRCPFField, self).__init__(max_length=14, min_length=11, *args, **kwargs)
     103    def __init__(self, always_return_formatted=False,
     104                 return_format=u'%s.%s.%s-%s', *args, **kwargs):
     105        self.always_return_formatted = always_return_formatted
     106        self.return_format = return_format
     107        super(BRCPFField, self).__init__(max_length=14, min_length=11,
     108                                         *args, **kwargs)
    101109
    102110    def clean(self, value):
    103111        """
     
    116124            raise ValidationError(self.error_messages['digits_only'])
    117125        if len(value) != 11:
    118126            raise ValidationError(self.error_messages['max_digits'])
     127
     128        # exclude cases of only 0 or only 9 digits
     129        if value in ('0' * 11, '9' * 11):
     130            raise ValidationError(self.error_messages['invalid'])
     131
    119132        orig_dv = value[-2:]
    120 
    121133        new_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(10, 1, -1))])
    122134        new_1dv = DV_maker(new_1dv % 11)
    123135        value = value[:-2] + str(new_1dv) + value[-1]
     
    127139        if value[-2:] != orig_dv:
    128140            raise ValidationError(self.error_messages['invalid'])
    129141
     142        # return a formatted string if asked
     143        if self.always_return_formatted:
     144            value = re.sub(r'[-\.]', '', orig_value)
     145            return self.return_format % tuple(re.findall(r'(\d{2,3})', value))
     146
    130147        return orig_value
    131148
    132 class BRCNPJField(Field):
     149class BRCNPJField(CharField):
     150    """
     151    This field validates a CNPJ number or a CNPJ string. A CNPJ number is
     152    compounded by XX.XXX.XXX/XXXX-XX.
     153    By default, the cleaned value is in the same format as entered.
     154    If you'd like to keep a unique format for cleaned values use
     155    the parameters "always_return_formatted" set to `True` and
     156    adjust "return_format" to your needs, the default format is
     157    '%s.%s.%s/%s-%s'.
     158    """
    133159    default_error_messages = {
    134160        'invalid': _("Invalid CNPJ number."),
    135161        'digits_only': _("This field requires only numbers."),
    136162        'max_digits': _("This field requires at least 14 digits"),
    137163    }
     164   
     165    def __init__(self, always_return_formatted=False,
     166                 return_format=u'%s.%s.%s/%s-%s', *args, **kwargs):
     167        self.always_return_formatted = always_return_formatted
     168        self.return_format = return_format
     169        super(BRCNPJField, self).__init__(max_length=18, min_length=14,
     170                                          *args, **kwargs)   
    138171
    139172    def clean(self, value):
    140173        """
     
    163196        value = value[:-1] + str(new_2dv)
    164197        if value[-2:] != orig_dv:
    165198            raise ValidationError(self.error_messages['invalid'])
     199           
     200        if self.always_return_formatted:
     201            value = re.sub('[-/\.]', '', orig_value)
     202            m = re.match(r'(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})', value)
     203            return self.return_format % tuple(m.groups())
    166204
    167205        return orig_value
  • tests/regressiontests/forms/localflavor/br.py

     
    8585...
    8686ValidationError: [u'Invalid CNPJ number.']
    8787>>> f.clean('64.132.916/0001-88')
    88 '64.132.916/0001-88'
     88u'64.132.916/0001-88'
    8989>>> f.clean('64-132-916/0001-88')
    90 '64-132-916/0001-88'
     90u'64-132-916/0001-88'
    9191>>> f.clean('64132916/0001-88')
    92 '64132916/0001-88'
     92u'64132916/0001-88'
    9393>>> f.clean('64.132.916/0001-XX')
    9494Traceback (most recent call last):
    9595...
     
    9797>>> f = BRCNPJField(required=False)
    9898>>> f.clean('')
    9999u''
     100>>> f.clean('64.132.916/0001-8')
     101Traceback (most recent call last):
     102...
     103ValidationError: [u'This field requires at least 14 digits']
     104>>> f.clean('6413291600018')
     105Traceback (most recent call last):
     106...
     107ValidationError: [u'Ensure this value has at least 14 characters (it has 13).']
     108>>> f.clean('64.132.916/0001-889')
     109Traceback (most recent call last):
     110...
     111ValidationError: [u'Ensure this value has at most 18 characters (it has 19).']
     112>>> f = BRCNPJField(required=True, always_return_formatted=True)
     113>>> f.clean('12-345-678/9012-10')
     114Traceback (most recent call last):
     115...
     116ValidationError: [u'Invalid CNPJ number.']
     117>>> f.clean('64.132.916/0001-88')
     118u'64.132.916/0001-88'
     119>>> f.clean('64132916000188')
     120u'64.132.916/0001-88'
     121>>> f.clean('64132916/0001-88')
     122u'64.132.916/0001-88'
     123>>> f = BRCNPJField(required=True, always_return_formatted=True, return_format='%s%s%s%s%s')
     124>>> f.clean('')
     125Traceback (most recent call last):
     126...
     127ValidationError: [u'This field is required.']
     128>>> f.clean('64132916/0001-88')
     129u'64132916000188'
     130>>> f.clean('64132916000188')
     131u'64132916000188'
     132>>> f.clean('64.132.916/0001-88')
     133u'64132916000188'
    100134
    101135# BRCPFField #################################################################
    102136
     
    151185u''
    152186>>> f.clean(None)
    153187u''
     188>>> f = BRCPFField(always_return_formatted=True)
     189>>> f.clean('')
     190Traceback (most recent call last):
     191...
     192ValidationError: [u'This field is required.']
     193>>> f.clean('663.256.017-26')
     194u'663.256.017-26'
     195>>> f.clean('66325601726')
     196u'663.256.017-26'
     197>>> f = BRCPFField(always_return_formatted=True, return_format='%s%s%s%s')
     198>>> f.clean('663.256.017-26')
     199u'66325601726'
     200>>> f.clean('66325601726')
     201u'66325601726'
    154202
    155203# BRPhoneNumberField #########################################################
    156204
Back to Top