Ticket #3945: django_cnpj_localflavor_take2.diff
File django_cnpj_localflavor_take2.diff, 3.3 KB (added by , 18 years ago) |
---|
-
django/contrib/localflavor/br/forms.py
37 37 def __init__(self, attrs=None): 38 38 from br_states import STATE_CHOICES # relative import 39 39 super(BRStateSelect, self).__init__(attrs, choices=STATE_CHOICES) 40 41 def DV_maker(v): 42 if v >= 2: 43 return 11 - v 44 return 0 45 46 class BRCNPJField(Field): 47 def clean(self, value): 48 """ value can be either a string in the format XX.XXX.XXX/XXXX-XX 49 or a group of 14 characters. """ 50 value = super(BRCNPJField, self).clean(value) 51 if value in EMPTY_VALUES: 52 return u'' 53 orig_value = value[:] 54 if not value.isdigit(): 55 value = re.sub("[-/\.]", "", value) 56 try: 57 int(value) 58 except ValueError: 59 raise ValidationError(u"This field requires only numbers") 60 if len(value) != 14: 61 raise ValidationError( 62 gettext(u"This field requires at least 14 digits")) 63 orig_dv = value[-2:] 64 65 new_1dv = sum([i * int(value[idx]) 66 for idx, i in enumerate(range(5, 1, -1) + 67 range(9, 1, -1))]) 68 new_1dv = DV_maker(new_1dv % 11) 69 value = value[:-2] + str(new_1dv) + value[-1] 70 new_2dv = sum([i * int(value[idx]) 71 for idx, i in enumerate(range(6, 1, -1) + 72 range(9, 1, -1))]) 73 new_2dv = DV_maker(new_2dv % 11) 74 value = value[:-1] + str(new_2dv) 75 if (value[-2:] != orig_dv): 76 raise ValidationError(gettext(u"Invalid CNPJ number")) 77 78 return orig_value -
tests/regressiontests/forms/localflavor.py
800 800 >>> f.clean('12345-123') 801 801 u'12345-123' 802 802 803 # BRCNPJField ############################################################ 804 805 >>> from django.contrib.localflavor.br.forms import BRCNPJField 806 >>> f = BRCNPJField(required=True) 807 >>> f.clean('') 808 Traceback (most recent call last): 809 ... 810 ValidationError: [u'This field is required.'] 811 >>> f.clean('12-345-678/9012-10') 812 Traceback (most recent call last): 813 ... 814 ValidationError: [u'Invalid CNPJ number'] 815 >>> f.clean('12.345.678/9012-10') 816 Traceback (most recent call last): 817 ... 818 ValidationError: [u'Invalid CNPJ number'] 819 >>> f.clean('12345678/9012-10') 820 Traceback (most recent call last): 821 ... 822 ValidationError: [u'Invalid CNPJ number'] 823 >>> f.clean('64.132.916/0001-88') 824 '64.132.916/0001-88' 825 >>> f.clean('64-132-916/0001-88') 826 '64-132-916/0001-88' 827 >>> f.clean('64132916/0001-88') 828 '64132916/0001-88' 829 >>> f.clean('64.132.916/0001-XX') 830 Traceback (most recent call last): 831 ... 832 ValidationError: [u'This field requires only numbers'] 833 >>> f = BRCNPJField(required=False) 834 >>> f.clean('') 835 u'' 836 803 837 # BRPhoneNumberField ######################################################### 804 838 805 839 >>> from django.contrib.localflavor.br.forms import BRPhoneNumberField