Code

Ticket #4122: localflavor_cl.diff

File localflavor_cl.diff, 5.3 KB (added by marijn <marijn@…>, 7 years ago)
Line 
1Index: django/contrib/localflavor/cl/__init__.py
2===================================================================
3Index: django/contrib/localflavor/cl/forms.py
4===================================================================
5--- django/contrib/localflavor/cl/forms.py      (revision 0)
6+++ django/contrib/localflavor/cl/forms.py      (revision 0)
7@@ -0,0 +1,80 @@
8+"""
9+Chile specific form helpers.
10+"""
11+from django.newforms import ValidationError
12+from django.newforms.fields import RegexField, EMPTY_VALUES
13+from django.utils.translation import gettext
14+
15+class CLRutField(RegexField):
16+    """
17+    Chilean "Rol Unico Tributario" (RUT) field. This is the chilean national identification number.
18+    """
19+    def __init__(self, *args, **kwargs):
20+        if kwargs.get('strict')  == True:
21+            del kwargs['strict']
22+            super(CLRutField, self).__init__(r'^(\d{1,2}\.)?\d{3}\.\d{3}-[\dkK]$',
23+                error_message=gettext(u'Enter valid a Chilean Rut. The format is XX.XXX.XXX-X.'),
24+                *args, **kwargs)
25+        else: # We take it relaxed and format it     for the user,
26+                  # accepting RUTs that are validate, but do not exist in the real world.
27+            super(CLRutField, self).__init__(r'^[\d\.]{1,11}-?[\dkK]$',
28+                error_message=gettext(u'Enter valid a Chilean RUT'),
29+                *args, **kwargs)
30+       
31+    def clean(self, value):
32+        """
33+        Check and clean the chilean rut.
34+        """
35+        super(CLRutField, self).clean(value)
36+        if value in EMPTY_VALUES:
37+            return u''
38+        (rut, verificador) = self._canonify(value)
39+        if self._algorithm(rut) == verificador:
40+            return self._format(rut, verificador)
41+        else:
42+            raise ValidationError(u'The Chilean RUT is not valid.')
43+       
44+   
45+    def _algorithm(self, rut):
46+        """
47+        Takes RUT in pure canonical form, calculates the verifier digit.
48+        """
49+        suma  = 0
50+        multi = 2
51+        for r in rut[::-1]:
52+            suma  += int (r) * multi
53+            multi += 1
54+            if multi == 8:
55+                multi = 2
56+        rest = suma % 11
57+        rest = 11 - rest
58+        if rest == 11: return '0'
59+        elif rest == 10: return 'K'
60+        else: return str(rest)
61+
62+    def _canonify(self, rut):
63+        """
64+        Turns the rut into one normalized format. Returns a (rut, verifier) tuple.
65+        """
66+        rut = str(rut)
67+        rut = rut.replace(' ', '')
68+        rut = rut.replace('.', '')
69+        rut = rut.replace('-', '')
70+        return (rut[:-1], rut[-1])
71+
72+    def _format(self, code, verifier=None):
73+        """
74+        Formats the rut from canonical form to the common string representation.
75+        If verifier=None, then the last digit in 'code' is the verifier.
76+        """
77+        if(verifier == None):
78+            verifier = code[-1]
79+            code = code[:-1]
80+        while len(code) > 3 and (code.find('.') > 3 or code.find('.') == -1):
81+            if code.find('.') == -1:
82+                new_dot = -3
83+            else:
84+                new_dot = code.find('.')-3
85+            code = code[:new_dot] +'.'+code[new_dot:]   
86+        return '%s-%s' % (code, verifier)
87+
88Index: tests/regressiontests/forms/localflavor.py
89===================================================================
90--- tests/regressiontests/forms/localflavor.py  (revision 5059)
91+++ tests/regressiontests/forms/localflavor.py  (working copy)
92@@ -1052,4 +1052,69 @@
93 <option value="VIC">Victoria</option>
94 <option value="WA">Western Australia</option>
95 </select>
96+
97+
98+## CLRutField #############################################################
99+
100+CLRutField is a Field that checks the validity of the Chilean
101+personal identification number (RUT). It has two modes relaxed (default) and
102+strict.
103+
104+>>> from django.contrib.localflavor.cl.forms import CLRutField
105+>>> rut = CLRutField()
106+
107+>>> rut.clean('11-6')
108+'11-6'
109+>>> rut.clean('116')
110+'11-6'
111+
112+# valid format, bad verifier.
113+>>> rut.clean('11.111.111-0')
114+Traceback (most recent call last):
115+...
116+ValidationError: [u'The Chilean RUT is not valid.']
117+>>> rut.clean('111')
118+Traceback (most recent call last):
119+...
120+ValidationError: [u'The Chilean RUT is not valid.']
121+
122+>>> rut.clean('767484100')
123+'76.748.410-0'
124+>>> rut.clean('78.412.790-7')
125+'78.412.790-7'
126+>>> rut.clean('8.334.6043')
127+'8.334.604-3'
128+>>> rut.clean('76793310-K')
129+'76.793.310-K'
130+
131+Strict RUT usage (does not allow imposible values)
132+>>> rut = CLRutField(strict=True)
133+
134+>>> rut.clean('11-6')
135+Traceback (most recent call last):
136+...
137+ValidationError: [u'Enter valid a Chilean Rut. The format is XX.XXX.XXX-X.']
138+
139+# valid format, bad verifier.
140+>>> rut.clean('11.111.111-0')
141+Traceback (most recent call last):
142+...
143+ValidationError: [u'The Chilean RUT is not valid.']
144+
145+# Correct input, invalid format.
146+>>> rut.clean('767484100')
147+Traceback (most recent call last):
148+...
149+ValidationError: [u'Enter valid a Chilean Rut. The format is XX.XXX.XXX-X.']
150+>>> rut.clean('78.412.790-7')
151+'78.412.790-7'
152+>>> rut.clean('8.334.6043')
153+Traceback (most recent call last):
154+...
155+ValidationError: [u'Enter valid a Chilean Rut. The format is XX.XXX.XXX-X.']
156+>>> rut.clean('76793310-K')
157+Traceback (most recent call last):
158+...
159+ValidationError: [u'Enter valid a Chilean Rut. The format is XX.XXX.XXX-X.']
160+
161 """