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

1234567891011121314151617181920212223242526272829303132333435363738
  1. from django.forms import fields, TextInput
  2. from oscar.core import validators
  3. class ExtendedURLField(fields.URLField):
  4. """
  5. Custom field similar to URLField type field, however also accepting and
  6. validating local relative URLs, ie. '/product/'
  7. """
  8. default_validators = []
  9. # Django 1.6 renders URLInput as <input type=url>, which causes some
  10. # browsers to require the input to be a valid absolute URL. As relative
  11. # URLS are allowed for ExtendedURLField, we must set it to TextInput
  12. widget = TextInput
  13. def __init__(self, max_length=None, min_length=None, verify_exists=None,
  14. *args, **kwargs):
  15. # We don't pass on verify_exists as it has been deprecated in Django
  16. # 1.4
  17. super(fields.URLField, self).__init__(
  18. max_length, min_length, *args, **kwargs)
  19. # Even though it is deprecated, we still pass on 'verify_exists' as
  20. # Oscar's ExtendedURLValidator uses it to determine whether to test
  21. # local URLs.
  22. if verify_exists is not None:
  23. validator = validators.ExtendedURLValidator(
  24. verify_exists=verify_exists)
  25. else:
  26. validator = validators.ExtendedURLValidator()
  27. self.validators.append(validator)
  28. def to_python(self, value):
  29. # We need to avoid having 'http' inserted at the start of
  30. # every value so that local URLs are valid.
  31. if value and value.startswith('/'):
  32. return value
  33. return super(ExtendedURLField, self).to_python(value)