Django:如何在数据库中将复选框的POST.get保存为false(0)? [英] Django: How to save the POST.get of a checkbox as false (0) in a DataBase?

查看:126
本文介绍了Django:如何在数据库中将复选框的POST.get保存为false(0)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在数据库中将复选框的值保存为true或false。我必须为此使用模型。如果选中此框,则将保存 1的值。但是,如果未选中此框,则会收到错误消息:

I'm trying to save the value of a checkbox as true or false in a database. I have to use a model for this. If the box is checked the value of '1' is saved. However, if the box is not checked I get the error message:

Django Version:     1.9.4
Exception Type:     IntegrityError
Exception Value:    (1048, "Column 'completed' cannot be null")

当前我的设置如下:

在models.py中,我有:

In models.py I have:

class myClass(models.Model): 
    completed = models.BooleanField(default=False, blank=True)

在views.py中,我有:

In views.py I have:

def create_myClass(request):
    completed = request.POST.get('completed')
    toSave = models.myClass(completed=completed)
    toSave.save()

,在HTML中,我有:

and in the HTML I have:

<label class="col-md-5" for="completed"> Completed: </label>
<input id="completed" type="checkbox" name="completed">


我已经试图在BooleanField中将required = False设置为其他一些帖子所建议的,但是随后得到错误: TypeError:__init __()得到了意外的关键字参数'required'

I've tried to set required = False in the BooleanField as some other posts suggested but then get the error: TypeError: __init__() got an unexpected keyword argument 'required'.

我还尝试在views.py中将 completed设置为False,例如:

I've also tried to set 'completed' to False in views.py like:

if request.POST.get('completed', False ):
    commpleted = False

completed = request.POST.get('completed')
if completed == 'null':
    commpleted = False

但均无效(不确定我的语法是否正确) ?)

But neither work (not sure if my syntax is correct?)

任何想法或建议都将不胜感激!

Any ideas or suggestions are greatly appreciated!

推荐答案

您可以打印 request.POST 的值

如果未在复选框HTML元素中指定 value 属性,则如果选中此复选框,则在 POST 中传递的默认值为上。

If you have not specified a value attribute in the checkbox HTML element, the default value which will passed in the POST is on if the checkbox is checked.

在视图中,您可以检查已完成的值是否在上

In the views you can check if the value of completed is on:

# this will set completed to True, only if the value of 
# `completed` passed in the POST is on 
completed = request.POST.get('completed', '') == 'on'

如果未选中此复选框,则不会传递任何内容,在这种情况下,您将从上述语句中得到 False

If the checkbox is not checked, then nothing will be passed and in that case you will get False from above statement.

我建议您使用 Django模式lForm (如果可以),大多数事情都会自动为您保重。

I would suggest that you use a Django ModelForm if you can so most of the things are automatically taken care for you.

这篇关于Django:如何在数据库中将复选框的POST.get保存为false(0)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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