PageRenderTime 18ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/localflavor/uy/forms.py

https://code.google.com/p/mango-py/
Python | 60 lines | 47 code | 5 blank | 8 comment | 0 complexity | 6c5b0b1c3f897666196c4bd4968fdcba MD5 | raw file
Possible License(s): BSD-3-Clause
  1. # -*- coding: utf-8 -*-
  2. """
  3. UY-specific form helpers.
  4. """
  5. import re
  6. from django.core.validators import EMPTY_VALUES
  7. from django.forms.fields import Select, RegexField
  8. from django.forms import ValidationError
  9. from django.utils.translation import ugettext_lazy as _
  10. from django.contrib.localflavor.uy.util import get_validation_digit
  11. class UYDepartamentSelect(Select):
  12. """
  13. A Select widget that uses a list of Uruguayan departaments as its choices.
  14. """
  15. def __init__(self, attrs=None):
  16. from uy_departaments import DEPARTAMENT_CHOICES
  17. super(UYDepartamentSelect, self).__init__(attrs, choices=DEPARTAMENT_CHOICES)
  18. class UYCIField(RegexField):
  19. """
  20. A field that validates Uruguayan 'Cedula de identidad' (CI) numbers.
  21. """
  22. default_error_messages = {
  23. 'invalid': _("Enter a valid CI number in X.XXX.XXX-X,"
  24. "XXXXXXX-X or XXXXXXXX format."),
  25. 'invalid_validation_digit': _("Enter a valid CI number."),
  26. }
  27. def __init__(self, *args, **kwargs):
  28. super(UYCIField, self).__init__(r'(?P<num>(\d{6,7}|(\d\.)?\d{3}\.\d{3}))-?(?P<val>\d)',
  29. *args, **kwargs)
  30. def clean(self, value):
  31. """
  32. Validates format and validation digit.
  33. The official format is [X.]XXX.XXX-X but usually dots and/or slash are
  34. omitted so, when validating, those characters are ignored if found in
  35. the correct place. The three typically used formats are supported:
  36. [X]XXXXXXX, [X]XXXXXX-X and [X.]XXX.XXX-X.
  37. """
  38. value = super(UYCIField, self).clean(value)
  39. if value in EMPTY_VALUES:
  40. return u''
  41. match = self.regex.match(value)
  42. if not match:
  43. raise ValidationError(self.error_messages['invalid'])
  44. number = int(match.group('num').replace('.', ''))
  45. validation_digit = int(match.group('val'))
  46. if not validation_digit == get_validation_digit(number):
  47. raise ValidationError(self.error_messages['invalid_validation_digit'])
  48. return value