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