只有一个BooleanField的Django表单 [英] Django form with just a BooleanField

查看:358
本文介绍了只有一个BooleanField的Django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我比较喜欢Django,而我正在使用Django 1.0。
我有这个:

forms.py:

  class MyForm(forms.Form) :
extra_cheeze = forms.BooleanField(required = False,
initial = False,
label ='Extra cheeze')

views.py:

  def order_something(request):
form = MyForm(request.POST或None)
如果request.method =='POST'和form.is_valid():
#do stuff ...

问题是表单无效,除非勾选该复选框,因此似乎没有办法获取False值从现场。
据我所知,从文档,它应该工作。如果我添加一个CharField到我的表单...它是有效的...



我误会了这里的东西,还是这个bug? (是的,我已经搜索,但没有发现任何相关)



更新:根据@Dominic Rodger的建议,我尝试添加隐藏字段>
dummy = forms.CharField(ini​​tial ='dummy',widget = forms.widgets.HiddenInput())

表格有效。这个解决方法使我能够立即移动,但是如果我误会某些东西,这仍然是有趣的。

解决方案

p>在我的问题的代码中有一个错误。感谢@ d0ugal帮助我发现它包括一个略有不同的例子。问题出在这里:

  form = MyForm(request.POST或None)#<  - 这里有问题!!!!! !!!!!!!!!!! 
如果request.method =='POST'和form.is_valid():
#做东西...

错误是我假设request.POST将评估为True,如果它是一个帖子。但是由于浏览器不发布任何未检查的复选框,而是唯一的字段,POST数据是一个空字典,其计算结果为False。这导致无法用作初始化数据,导致表单无法绑定且无效。

@ d0ugal的示例首先执行安全的事情并测试request.method。


I'm rather new to Django and I'm using Django 1.0. I have this:
forms.py:

class MyForm(forms.Form):
    extra_cheeze = forms.BooleanField(required=False,
                                      initial=False,
                                      label='Extra cheeze')

views.py:

def order_something(request):
    form = MyForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        # do stuff...

The problem is that the form is not valid unless the checkbox is checked, so there doesn't seem to be a way to get a False value from the field. As far as I can understand from the docs, it should work. It works if I add a CharField to my form...

Am I misunderstanding something here or is this a bug? (Yes, I have googled but found nothing relevant)

Update: As suggested by @Dominic Rodger, I tried adding a hidden field
dummy = forms.CharField(initial='dummy', widget=forms.widgets.HiddenInput())
and that makes the form valid. This workaround enables me to move on right now, but it would still be interesting to know if I'm misunderstanding something...

解决方案

There was a bug in the code in my question. Thanks to @d0ugal for helping me spot it by including a slightly different example. The problem was here:

form = MyForm(request.POST or None) # <- PROBLEM HERE!!!!!!!!!!!!!!!!
if request.method == 'POST' and form.is_valid():
    # do stuff...

The bug was that I assumed that request.POST would evaluate to True if it was a post. But since browsers don't post anything for a not-checked checkbox, and that was the only field, the POST data was an empty dictionary, which evaluates to False. This caused None to be used as initialization data, causing the form to be unbound and not valid.
@d0ugal's example does the safe thing and tests request.method first.

这篇关于只有一个BooleanField的Django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆