Debian Codegraph @

django/contrib/postgres/validators.py

raw
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
12
13 class ArrayMaxLengthValidator(MaxLengthValidator):
14 message = ngettext_lazy(
15 "List contains %(show_value)d item, it should contain no more than "
16 "%(limit_value)d.",
17 "List contains %(show_value)d items, it should contain no more than "
18 "%(limit_value)d.",
19 "show_value",
20 )
21
22
23 class ArrayMinLengthValidator(MinLengthValidator):
24 message = ngettext_lazy(
25 "List contains %(show_value)d item, it should contain no fewer than "
26 "%(limit_value)d.",
27 "List contains %(show_value)d items, it should contain no fewer than "
28 "%(limit_value)d.",
29 "show_value",
30 )
31
32
33 @deconstructible
34 class KeysValidator:
35 """A validator designed for HStore to require/restrict keys."""
36
37 messages = {
38 "missing_keys": _("Some keys were missing: %(keys)s"),
39 "extra_keys": _("Some unknown keys were provided: %(keys)s"),
40 }
41 strict = False
42
43 def __init__(self, keys, strict=False, messages=None):
44 self.keys = set(keys)
45 self.strict = strict
46 if messages is not None:
47 self.messages = {**self.messages, **messages}
48
49 def __call__(self, value):
50 keys = set(value)
51 missing_keys = self.keys - keys
52 if missing_keys:
53 raise ValidationError(
54 self.messages["missing_keys"],
55 code="missing_keys",
56 params={"keys": ", ".join(missing_keys)},
57 )
58 if self.strict:
59 extra_keys = keys - self.keys
60 if extra_keys:
61 raise ValidationError(
62 self.messages["extra_keys"],
63 code="extra_keys",
64 params={"keys": ", ".join(extra_keys)},
65 )
66
67 def __eq__(self, other):
68 return (
69 isinstance(other, self.__class__)
70 and self.keys == other.keys
71 and self.messages == other.messages
72 and self.strict == other.strict
73 )
74
75
76 class RangeMaxValueValidator(MaxValueValidator):
77 def compare(self, a, b):
78 return a.upper is None or a.upper > b
79
80 message = _(
81 "Ensure that the upper bound of the range is not greater than %(limit_value)s."
82 )
83
84
85 class RangeMinValueValidator(MinValueValidator):
86 def compare(self, a, b):
87 return a.lower is None or a.lower < b
88
89 message = _(
90 "Ensure that the lower bound of the range is not less than %(limit_value)s."
91 )