|
1 """ |
|
2 India-specific Form helpers. |
|
3 """ |
|
4 |
|
5 from django.newforms import ValidationError |
|
6 from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES |
|
7 from django.utils.encoding import smart_unicode |
|
8 from django.utils.translation import gettext |
|
9 import re |
|
10 |
|
11 |
|
12 class INZipCodeField(RegexField): |
|
13 default_error_messages = { |
|
14 'invalid': gettext(u'Enter a zip code in the format XXXXXXX.'), |
|
15 } |
|
16 |
|
17 def __init__(self, *args, **kwargs): |
|
18 super(INZipCodeField, self).__init__(r'^\d{6}$', |
|
19 max_length=None, min_length=None, *args, **kwargs) |
|
20 |
|
21 class INStateField(Field): |
|
22 """ |
|
23 A form field that validates its input is a Indian state name or |
|
24 abbreviation. It normalizes the input to the standard two-letter vehicle |
|
25 registration abbreviation for the given state or union territory |
|
26 """ |
|
27 default_error_messages = { |
|
28 'invalid': u'Enter a Indian state or territory.', |
|
29 } |
|
30 |
|
31 def clean(self, value): |
|
32 from in_states import STATES_NORMALIZED |
|
33 super(INStateField, self).clean(value) |
|
34 if value in EMPTY_VALUES: |
|
35 return u'' |
|
36 try: |
|
37 value = value.strip().lower() |
|
38 except AttributeError: |
|
39 pass |
|
40 else: |
|
41 try: |
|
42 return smart_unicode(STATES_NORMALIZED[value.strip().lower()]) |
|
43 except KeyError: |
|
44 pass |
|
45 raise ValidationError(self.error_messages['invalid']) |
|
46 |
|
47 class INStateSelect(Select): |
|
48 """ |
|
49 A Select widget that uses a list of Indian states/territories as its |
|
50 choices. |
|
51 """ |
|
52 def __init__(self, attrs=None): |
|
53 from in_states import STATE_CHOICES |
|
54 super(INStateSelect, self).__init__(attrs, choices=STATE_CHOICES) |
|
55 |