mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-28 17:09:59 +03:00
Make NullBooleanField
subclass BooleanField
This removes a lot of the redundancy that was in place becuase we were not doing this. This maintains the `None` initial value that was previously present, as well as disallowing `allow_null` to be passed in.
This commit is contained in:
parent
373e521f36
commit
a07a71a8f5
|
@ -740,56 +740,14 @@ class BooleanField(Field):
|
||||||
return bool(value)
|
return bool(value)
|
||||||
|
|
||||||
|
|
||||||
class NullBooleanField(Field):
|
class NullBooleanField(BooleanField):
|
||||||
default_error_messages = {
|
|
||||||
'invalid': _('Must be a valid boolean.')
|
|
||||||
}
|
|
||||||
initial = None
|
initial = None
|
||||||
TRUE_VALUES = {
|
|
||||||
't', 'T',
|
|
||||||
'y', 'Y', 'yes', 'YES',
|
|
||||||
'true', 'True', 'TRUE',
|
|
||||||
'on', 'On', 'ON',
|
|
||||||
'1', 1,
|
|
||||||
True
|
|
||||||
}
|
|
||||||
FALSE_VALUES = {
|
|
||||||
'f', 'F',
|
|
||||||
'n', 'N', 'no', 'NO',
|
|
||||||
'false', 'False', 'FALSE',
|
|
||||||
'off', 'Off', 'OFF',
|
|
||||||
'0', 0, 0.0,
|
|
||||||
False
|
|
||||||
}
|
|
||||||
NULL_VALUES = {'null', 'Null', 'NULL', '', None}
|
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
|
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
|
||||||
kwargs['allow_null'] = True
|
kwargs['allow_null'] = True
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
|
|
||||||
def to_internal_value(self, data):
|
|
||||||
try:
|
|
||||||
if data in self.TRUE_VALUES:
|
|
||||||
return True
|
|
||||||
elif data in self.FALSE_VALUES:
|
|
||||||
return False
|
|
||||||
elif data in self.NULL_VALUES:
|
|
||||||
return None
|
|
||||||
except TypeError: # Input is an unhashable type
|
|
||||||
pass
|
|
||||||
self.fail('invalid', input=data)
|
|
||||||
|
|
||||||
def to_representation(self, value):
|
|
||||||
if value in self.NULL_VALUES:
|
|
||||||
return None
|
|
||||||
if value in self.TRUE_VALUES:
|
|
||||||
return True
|
|
||||||
elif value in self.FALSE_VALUES:
|
|
||||||
return False
|
|
||||||
return bool(value)
|
|
||||||
|
|
||||||
|
|
||||||
# String types...
|
# String types...
|
||||||
|
|
||||||
class CharField(Field):
|
class CharField(Field):
|
||||||
|
|
Loading…
Reference in New Issue
Block a user