validators.py 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. import re
  2. from django.conf import settings
  3. from django.core.validators import _lazy_re_compile, BaseValidator, URLValidator
  4. class EnhancedURLValidator(URLValidator):
  5. """
  6. Extends Django's built-in URLValidator to permit the use of hostnames with no domain extension and enforce allowed
  7. schemes specified in the configuration.
  8. """
  9. fqdn_re = URLValidator.hostname_re + URLValidator.domain_re + URLValidator.tld_re
  10. host_res = [URLValidator.ipv4_re, URLValidator.ipv6_re, fqdn_re, URLValidator.hostname_re]
  11. regex = _lazy_re_compile(
  12. r'^(?:[a-z0-9\.\-\+]*)://' # Scheme (enforced separately)
  13. r'(?:\S+(?::\S*)?@)?' # HTTP basic authentication
  14. r'(?:' + '|'.join(host_res) + ')' # IPv4, IPv6, FQDN, or hostname
  15. r'(?::\d{2,5})?' # Port number
  16. r'(?:[/?#][^\s]*)?' # Path
  17. r'\Z', re.IGNORECASE)
  18. schemes = settings.ALLOWED_URL_SCHEMES
  19. class ExclusionValidator(BaseValidator):
  20. """
  21. Ensure that a field's value is not equal to any of the specified values.
  22. """
  23. message = 'This value may not be %(show_value)s.'
  24. def compare(self, a, b):
  25. return a in b