对 Python 等动态语言的进一步认知

2019-08-01  本文已影响0人  武曌思

起因

Django 的 django.forms.BooleanField 不能传递 false,如果想传,必须加上 required=False。

但这样就和参数的必需性混了。


过程

查看 BooleanField 源码

    def to_python(self, value):
        """Returns a Python boolean object."""
        # Explicitly check for the string 'False', which is what a hidden field
        # will submit for False. Also check for '0', since this is what
        # RadioSelect will provide. Because bool("True") == bool('1') == True,
        # we don't need to handle that explicitly.
        if isinstance(value, six.string_types) and value.lower() in ('false', '0'):
            value = False
        else:
            value = bool(value)
        return super(BooleanField, self).to_python(value)

    def validate(self, value):
        if not value and self.required:
            raise ValidationError(self.error_messages['required'], code='required')

主要是 validate 函数中,false 会触发 not value,所以才不能传 false。


解决方法

我可以动态的修改 BooleanField 的方法,参考了 django.forms.NullBooleanField 的实现,如下:

from django.core.exceptions import ValidationError

from django.forms import BooleanField


def to_python(self, value):
    if value in (True, 'True', 'true', '1'):
        return True
    elif value in (False, 'False', 'false', '0'):
        return False
    else:
        return None


def validate(self, value):
    if value is None and self.required:
        raise ValidationError(self.error_messages['required'], code='required')


print('修复 django.forms.BooleanField 不能传 FALSE 的 bug')
BooleanField.to_python = to_python
BooleanField.validate = validate


认知

上一篇 下一篇

猜你喜欢

热点阅读