Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

validators.py 2.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from django.core import validators
  2. from django.core.exceptions import ValidationError
  3. from django.core.urlresolvers import resolve
  4. from django.db.models import get_model
  5. from django.http import Http404
  6. from django.utils.translation import ugettext_lazy as _
  7. class ExtendedURLValidator(validators.URLValidator):
  8. def __init__(self, *args, **kwargs):
  9. # 'verify_exists' has been removed in Django 1.5 and so we no longer
  10. # pass it up to the core validator class
  11. self.is_local_url = False
  12. verify_exists = kwargs.pop('verify_exists', False)
  13. super(ExtendedURLValidator, self).__init__(*args, **kwargs)
  14. self.verify_exists = verify_exists
  15. def __call__(self, value):
  16. try:
  17. super(ExtendedURLValidator, self).__call__(value)
  18. except ValidationError:
  19. # The parent validator will raise an exception if the URL does not
  20. # exist and so we test here to see if the value is a local URL.
  21. if self.verify_exists and value:
  22. self.validate_local_url(value)
  23. else:
  24. raise
  25. def validate_local_url(self, value):
  26. value = self.clean_url(value)
  27. try:
  28. resolve(value)
  29. except Http404:
  30. # We load flatpages here as it causes a circular reference problem
  31. # sometimes. FlatPages is None if not installed
  32. FlatPage = get_model('flatpages', 'FlatPage')
  33. if FlatPage is not None:
  34. try:
  35. FlatPage.objects.get(url=value)
  36. except FlatPage.DoesNotExist:
  37. self.is_local_url = True
  38. else:
  39. return
  40. raise ValidationError(_('Specified page does not exist'))
  41. else:
  42. self.is_local_url = True
  43. def clean_url(self, value):
  44. """
  45. Ensure url has a preceding slash and no query string
  46. """
  47. if value != '/':
  48. value = '/' + value.lstrip('/')
  49. q_index = value.find('?')
  50. if q_index > 0:
  51. value = value[:q_index]
  52. return value
  53. class URLDoesNotExistValidator(ExtendedURLValidator):
  54. def __call__(self, value):
  55. """
  56. Validate that the URLdoes not already exist.
  57. The URL will be verified first and raises ``ValidationError`` when
  58. it is invalid. A valid URL is checked for existance and raises
  59. ``ValidationError`` if the URL already exists. Setting attribute
  60. ``verify_exists`` has no impact on validation.
  61. This validation uses two calls to ExtendedURLValidator which can
  62. be slow. Be aware of this, when you use it.
  63. Returns ``None`` if URL is valid and does not exist.
  64. """
  65. try:
  66. self.validate_local_url(value)
  67. except ValidationError:
  68. # Page exists - that is what we want
  69. return
  70. raise ValidationError(
  71. _('Specified page already exists!'), code='invalid')