You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

fields.py 4.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import six
  2. from django.core.exceptions import ImproperlyConfigured
  3. from django.db.models.fields import CharField, DecimalField, Field
  4. from django.db.models import SubfieldBase
  5. from django.utils import six as django_six
  6. from django.utils.translation import ugettext_lazy as _
  7. from django.core.validators import MaxLengthValidator
  8. from oscar.core import validators
  9. from oscar.forms import fields
  10. import oscar.core.phonenumber as phonenumber
  11. try:
  12. from south.modelsinspector import add_introspection_rules
  13. except ImportError:
  14. pass
  15. else:
  16. add_introspection_rules([], ["^oscar\.models\.fields\.ExtendedURLField$"])
  17. add_introspection_rules([], [
  18. "^oscar\.models\.fields\.PositiveDecimalField$"])
  19. add_introspection_rules([], [
  20. "^oscar\.models\.fields\.UppercaseCharField$"])
  21. add_introspection_rules([], [
  22. "^oscar\.models\.fields\.PhoneNumberField$"])
  23. class ExtendedURLField(CharField):
  24. description = _("URL")
  25. def __init__(self, verbose_name=None, name=None,
  26. verify_exists=None, **kwargs):
  27. kwargs['max_length'] = kwargs.get('max_length', 200)
  28. CharField.__init__(self, verbose_name, name, **kwargs)
  29. # 'verify_exists' was deprecated in Django 1.4. To ensure backwards
  30. # compatibility, it is still accepted here, but only passed
  31. # on to the parent class if it was specified.
  32. self.verify_exists = verify_exists
  33. if verify_exists is not None:
  34. validator = validators.ExtendedURLValidator(
  35. verify_exists=verify_exists)
  36. else:
  37. validator = validators.ExtendedURLValidator()
  38. self.validators.append(validator)
  39. def formfield(self, **kwargs):
  40. # As with CharField, this will cause URL validation to be performed
  41. # twice.
  42. defaults = {
  43. 'form_class': fields.ExtendedURLField,
  44. 'verify_exists': self.verify_exists
  45. }
  46. defaults.update(kwargs)
  47. return super(ExtendedURLField, self).formfield(**defaults)
  48. class PositiveDecimalField(DecimalField):
  49. """
  50. A simple subclass of ``django.db.models.fields.DecimalField`` that
  51. restricts values to be non-negative.
  52. """
  53. def formfield(self, **kwargs):
  54. return super(PositiveDecimalField, self).formfield(min_value=0)
  55. class UppercaseCharField(django_six.with_metaclass(SubfieldBase, CharField)):
  56. """
  57. A simple subclass of ``django.db.models.fields.CharField`` that
  58. restricts all text to be uppercase.
  59. Defined with the with_metaclass helper so that to_python is called
  60. https://docs.djangoproject.com/en/1.6/howto/custom-model-fields/#the-subfieldbase-metaclass # NOQA
  61. """
  62. def to_python(self, value):
  63. val = super(UppercaseCharField, self).to_python(value)
  64. if isinstance(val, six.string_types):
  65. return val.upper()
  66. else:
  67. return val
  68. class PhoneNumberField(Field):
  69. """
  70. An international phone number.
  71. * Validates a wide range of phone number formats
  72. * Displays it nicely formatted
  73. * Can be given a hint for the country, so that it can accept local numbers,
  74. that are not in an international format
  75. Note:
  76. This field is based on work in django-phonenumber-field:
  77. https://github.com/maikhoepfel/django-phonenumber-field/
  78. See ``oscar/core/phonenumber.py`` for the relevant copyright and
  79. permission notice.
  80. """
  81. attr_class = phonenumber.PhoneNumber
  82. descriptor_class = phonenumber.PhoneNumberDescriptor
  83. default_validators = [phonenumber.validate_international_phonenumber]
  84. description = _("Phone number")
  85. def __init__(self, *args, **kwargs):
  86. if kwargs.get('null', False):
  87. raise ImproperlyConfigured(
  88. "null=True is not supported on PhoneNumberField")
  89. kwargs['max_length'] = kwargs.get('max_length', 128)
  90. super(PhoneNumberField, self).__init__(*args, **kwargs)
  91. self.validators.append(MaxLengthValidator(self.max_length))
  92. def get_internal_type(self):
  93. return "CharField"
  94. def get_prep_value(self, value):
  95. """
  96. Returns field's value prepared for saving into a database.
  97. """
  98. value = phonenumber.to_python(value)
  99. if value is None:
  100. return ''
  101. return value.as_e164 if value.is_valid() else value.raw_input
  102. def contribute_to_class(self, cls, name):
  103. super(PhoneNumberField, self).contribute_to_class(cls, name)
  104. setattr(cls, self.name, self.descriptor_class(self))