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

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