【问题标题】:Why does 0 in a GET request evaluate to True in a Django 1.10 form?为什么 GET 请求中的 0 在 Django 1.10 表单中评估为 True?
【发布时间】:2024-01-23 15:41:01
【问题描述】:

我将 GET 请求传递给包含参数“favorite”的 Django 表单。当我执行 localhost:8000?favorite=1 时,它工作正常。正如我所期望的那样,1 评估为 True。但是,当我执行 localhost:8000?favorite=0, 0 时,也会评估为 True,这不是我所期望的。当我直接查看 request.GET['favorite'] 时,在它被 FavoriteForm 类评估之前,我看到它等于 0。但是,FavoriteForm 类似乎正在将其转换为 True,我不知道为什么.我假设它将 0 视为一个字符串,并将所有字符串评估为 True,但是这就是他们设置它的方式没有意义,因为它违反直觉,所以我想肯定还有其他事情发生开,比如我的表格配置错误之类的。想法?

forms.py

class FavoriteForm(forms.Form):
    favorite = forms.BooleanField()

views.py

if request.method == 'GET':
    form = FavoriteForm(request.GET)
favorite = form.cleaned_data['favorite']
print favorite #This returns True if request.GET['favorite'] == 0
print request.GET['favorite'] #This returns 0 as expected

查询

http://localhost:8000?favorite=0

【问题讨论】:

  • 另外,如果我执行 def clean(self):cleaned_data = super(FavoriteForm, self).clean() favorite =clean_data.get("favorite") raise Exception(favorite),这将返回 True同样,所以看起来 clean 方法是把事情搞砸了。
  • 检查cleaned_data.get("favorite") 没有返回str,因为任何非空字符串(甚至"0")都是真实的。
  • 等等,我刚刚检查了 raise Exception(bool("0")),它的评估结果为 True。什么?
  • @kloddant bool("0") 的计算结果为 True,因为 "0" 是一个字符串,因此如上所述。试试bool("False")。它也评估为 True。如果您真的想查看 0 的布尔值,请执行以下操作:bool(int("0")),返回 False。

标签: python django forms get boolean


【解决方案1】:

print favorite return True 表示 0、1 或 et.c 是字符串 为了获得正确的结果,请这样写: 查询

http://localhost:8000?favorite=true

http://localhost:8000?favorite=false

【讨论】:

  • 哦,现在可以了!我发誓我试过了,它返回了 True。好的,非常感谢!
  • 太棒了 :) 一点也不
【解决方案2】:

好的,我有一个解决方案,但我不喜欢它。它涉及修改 request.GET 以在将任何字符串传递给表单类之前将其评估为布尔值。由于 request.GET 永远不会返回任何不是字符串的东西,看起来 Django 真的应该在其表单类中将“0”视为 0。

utils.py

def boolean(string):
    response = None
    if string is 0 or string is None:
        response = False
    if string is 1:
        response = True
    if isinstance(string, basestring):
        if string.lower() in ["0", "no", "false"]:
            response = False
        if string.lower() in ["1", "yes", "true"]:
            response = True
    return response

forms.py

class FavoriteForm(forms.Form):
    favorite = forms.BooleanField(required=False)

views.py

from utils import boolean

if request.method == 'GET':
    if 'favorite' in request.GET:
        request.GET._mutable = True
        request.GET['favorite'] = boolean(request.GET['favorite'])

【讨论】:

    最近更新 更多