validators.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from django.core.exceptions import ValidationError
  2. from django.core.validators import (
  3. MaxLengthValidator,
  4. MaxValueValidator,
  5. MinLengthValidator,
  6. MinValueValidator,
  7. )
  8. from django.utils.deconstruct import deconstructible
  9. from django.utils.translation import gettext_lazy as _
  10. from django.utils.translation import ngettext_lazy
  11. class ArrayMaxLengthValidator(MaxLengthValidator):
  12. message = ngettext_lazy(
  13. "List contains %(show_value)d item, it should contain no more than "
  14. "%(limit_value)d.",
  15. "List contains %(show_value)d items, it should contain no more than "
  16. "%(limit_value)d.",
  17. "show_value",
  18. )
  19. class ArrayMinLengthValidator(MinLengthValidator):
  20. message = ngettext_lazy(
  21. "List contains %(show_value)d item, it should contain no fewer than "
  22. "%(limit_value)d.",
  23. "List contains %(show_value)d items, it should contain no fewer than "
  24. "%(limit_value)d.",
  25. "show_value",
  26. )
  27. @deconstructible
  28. class KeysValidator:
  29. """A validator designed for HStore to require/restrict keys."""
  30. messages = {
  31. "missing_keys": _("Some keys were missing: %(keys)s"),
  32. "extra_keys": _("Some unknown keys were provided: %(keys)s"),
  33. }
  34. strict = False
  35. def __init__(self, keys, strict=False, messages=None):
  36. self.keys = set(keys)
  37. self.strict = strict
  38. if messages is not None:
  39. self.messages = {**self.messages, **messages}
  40. def __call__(self, value):
  41. keys = set(value)
  42. missing_keys = self.keys - keys
  43. if missing_keys:
  44. raise ValidationError(
  45. self.messages["missing_keys"],
  46. code="missing_keys",
  47. params={"keys": ", ".join(missing_keys)},
  48. )
  49. if self.strict:
  50. extra_keys = keys - self.keys
  51. if extra_keys:
  52. raise ValidationError(
  53. self.messages["extra_keys"],
  54. code="extra_keys",
  55. params={"keys": ", ".join(extra_keys)},
  56. )
  57. def __eq__(self, other):
  58. return (
  59. isinstance(other, self.__class__)
  60. and self.keys == other.keys
  61. and self.messages == other.messages
  62. and self.strict == other.strict
  63. )
  64. class RangeMaxValueValidator(MaxValueValidator):
  65. def compare(self, a, b):
  66. return a.upper is None or a.upper > b
  67. message = _(
  68. "Ensure that the upper bound of the range is not greater than %(limit_value)s."
  69. )
  70. class RangeMinValueValidator(MinValueValidator):
  71. def compare(self, a, b):
  72. return a.lower is None or a.lower < b
  73. message = _(
  74. "Ensure that the lower bound of the range is not less than %(limit_value)s."
  75. )