blob: a60c344ebd84007fa4e1068eab6d7054a0d129fd (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
from django.core.exceptions import ValidationError
from django.forms import NullBooleanField
class StrictBooleanField(NullBooleanField):
"""
forms.BooleanField coerces almost any truthy input to True. Delegate to
NullBooleanField's stricter parsing while still rejecting None values.
"""
def to_python(self, value):
# The admin changelist search allows case-insensitivity.
try:
value = value.lower()
except AttributeError:
pass
value = super().to_python(value)
if value is None:
# Not translated, as this is currently not user-facing.
raise ValidationError("Invalid value.")
return value
class StrictNullBooleanField(NullBooleanField):
"""
forms.NullBooleanField doesn't distinguish explicit None values, so check
for that before delegating.
"""
def to_python(self, value):
# The admin changelist search allows case-insensitivity.
try:
value = value.lower()
except AttributeError:
pass
if value in (None, "none"):
return None
value = super().to_python(value)
if value is None:
# Not translated, as this is currently not user-facing.
raise ValidationError("Invalid value.")
return value
|