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 5.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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\.NullCharField$"])
  23. add_introspection_rules([], [
  24. "^oscar\.models\.fields\.PhoneNumberField$"])
  25. class ExtendedURLField(CharField):
  26. description = _("URL")
  27. def __init__(self, verbose_name=None, name=None,
  28. verify_exists=None, **kwargs):
  29. kwargs['max_length'] = kwargs.get('max_length', 200)
  30. CharField.__init__(self, verbose_name, name, **kwargs)
  31. # 'verify_exists' was deprecated in Django 1.4. To ensure backwards
  32. # compatibility, it is still accepted here, but only passed
  33. # on to the parent class if it was specified.
  34. self.verify_exists = verify_exists
  35. if verify_exists is not None:
  36. validator = validators.ExtendedURLValidator(
  37. verify_exists=verify_exists)
  38. else:
  39. validator = validators.ExtendedURLValidator()
  40. self.validators.append(validator)
  41. def formfield(self, **kwargs):
  42. # As with CharField, this will cause URL validation to be performed
  43. # twice.
  44. defaults = {
  45. 'form_class': fields.ExtendedURLField,
  46. 'verify_exists': self.verify_exists
  47. }
  48. defaults.update(kwargs)
  49. return super(ExtendedURLField, self).formfield(**defaults)
  50. class PositiveDecimalField(DecimalField):
  51. """
  52. A simple subclass of ``django.db.models.fields.DecimalField`` that
  53. restricts values to be non-negative.
  54. """
  55. def formfield(self, **kwargs):
  56. return super(PositiveDecimalField, self).formfield(min_value=0)
  57. class UppercaseCharField(django_six.with_metaclass(SubfieldBase, CharField)):
  58. """
  59. A simple subclass of ``django.db.models.fields.CharField`` that
  60. restricts all text to be uppercase.
  61. Defined with the with_metaclass helper so that to_python is called
  62. https://docs.djangoproject.com/en/1.6/howto/custom-model-fields/#the-subfieldbase-metaclass # NOQA
  63. """
  64. def to_python(self, value):
  65. val = super(UppercaseCharField, self).to_python(value)
  66. if isinstance(val, six.string_types):
  67. return val.upper()
  68. else:
  69. return val
  70. class NullCharField(CharField):
  71. """
  72. CharField that stores '' as None and returns None as ''
  73. Useful when using unique=True and forms. Implies null==blank==True.
  74. When a ModelForm with a CharField with null=True gets saved, the field will
  75. be set to '': https://code.djangoproject.com/ticket/9590
  76. This breaks usage with unique=True, as '' is considered equal to another
  77. field set to ''.
  78. """
  79. description = "CharField that stores '' as None and returns None as ''"
  80. # necessary for to_python to be called
  81. __metaclass__ = SubfieldBase
  82. def __init__(self, *args, **kwargs):
  83. if not kwargs.get('null', True) or not kwargs.get('blank', True):
  84. raise ImproperlyConfigured(
  85. "NullCharField implies null==blank==True")
  86. kwargs['null'] = kwargs['blank'] = True
  87. super(NullCharField, self).__init__(*args, **kwargs)
  88. def to_python(self, value):
  89. if isinstance(value, CharField):
  90. return value
  91. if value is None:
  92. return u""
  93. else:
  94. return value
  95. def get_prep_value(self, value):
  96. prepped = super(NullCharField, self).get_prep_value(value)
  97. if prepped == "":
  98. return None
  99. else:
  100. return prepped
  101. class PhoneNumberField(Field):
  102. """
  103. An international phone number.
  104. * Validates a wide range of phone number formats
  105. * Displays it nicely formatted
  106. * Can be given a hint for the country, so that it can accept local numbers,
  107. that are not in an international format
  108. Note:
  109. This field is based on work in django-phonenumber-field:
  110. https://github.com/maikhoepfel/django-phonenumber-field/
  111. See ``oscar/core/phonenumber.py`` for the relevant copyright and
  112. permission notice.
  113. """
  114. attr_class = phonenumber.PhoneNumber
  115. descriptor_class = phonenumber.PhoneNumberDescriptor
  116. default_validators = [phonenumber.validate_international_phonenumber]
  117. description = _("Phone number")
  118. def __init__(self, *args, **kwargs):
  119. if kwargs.get('null', False):
  120. raise ImproperlyConfigured(
  121. "null=True is not supported on PhoneNumberField")
  122. kwargs['max_length'] = kwargs.get('max_length', 128)
  123. super(PhoneNumberField, self).__init__(*args, **kwargs)
  124. self.validators.append(MaxLengthValidator(self.max_length))
  125. def get_internal_type(self):
  126. return "CharField"
  127. def get_prep_value(self, value):
  128. """
  129. Returns field's value prepared for saving into a database.
  130. """
  131. value = phonenumber.to_python(value)
  132. if value is None:
  133. return ''
  134. return value.as_e164 if value.is_valid() else value.raw_input
  135. def contribute_to_class(self, cls, name):
  136. super(PhoneNumberField, self).contribute_to_class(cls, name)
  137. setattr(cls, self.name, self.descriptor_class(self))