gpt4 book ai didi

python - Django Forms BooleanField 单元测试用例有什么问题?

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:49 28 4
gpt4 key购买 nike

我完全被困在这里了。为什么这个测试用例会失败?

class BogusForm(forms.Form):
bogus_bool = forms.BooleanField()

class TestBogusForm(TestCase):

def test_bogus_false(self):
query_dict = QueryDict('', mutable=True)
query_dict.update({'bogus_bool': False})
bogus_form = BogusForm(query_dict)
self.assertTrue(bogus_form.is_valid())

表单字段验证失败,但前提是当我更新 QueryDict 时 bogus_bool 为 False。如果我说:

query_dict.update({'bogus_bool': True})

然后它通过验证。这里发生了什么?这是 Django Forms 中的错误吗?

如果我在将它传递给 BogusForm 构造函数之前查看 QueryDict,它看起来像这样:

<QueryDict: {u'bogus_bool': [False]}>

这对我来说看起来完全合法和正确。

最佳答案

来自 django 的 documentation

Since all Field subclasses have required=True by default, the validation condition here is important. If you want to include a boolean in your form that can be either True or False (e.g. a checked or unchecked checkbox), you must remember to pass in required=False when creating the BooleanField.

关于python - Django Forms BooleanField 单元测试用例有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10440937/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com