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.

__init__.py 6.0KB

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