我正在尝试将复选框的值保存为数据库中的true或false。我必须为此使用模型。如果选中此框,则将保存值“ 1”。但是,如果未选中此框,则会收到错误消息:
Django Version: 1.9.4
Exception Type: IntegrityError
Exception Value: (1048, "Column 'completed' cannot be null")
目前,我的设置如下所示:
在models.py中,我有:
class myClass(models.Model):
completed = models.BooleanField(default=False, blank=True)
在views.py中,我有:
def create_myClass(request):
completed = request.POST.get('completed')
toSave = models.myClass(completed=completed)
toSave.save()
在HTML中,我有:
<label class="col-md-5" for="completed"> Completed: </label>
<input id="completed" type="checkbox" name="completed">
我尝试在BooleanField中设置required = False,就像其他一些帖子所建议的那样,但随后出现错误:
TypeError: __init__() got an unexpected keyword argument 'required'
。我还尝试在views.py中将“ completed”设置为False,例如:
if request.POST.get('completed', False ):
commpleted = False
和
completed = request.POST.get('completed')
if completed == 'null':
commpleted = False
但是都没有用(不确定我的语法是否正确?)
任何想法或建议,不胜感激!
最佳答案
您可以打印request.POST
的值以查看视图中得到的内容。
如果未在复选框HTML元素中指定value
属性,则如果选中此复选框,则将在POST
中传递的默认值为on
。
在视图中,您可以检查completed
的值是否为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
。如果可以的话,我建议您使用Django ModelForm,这样大多数事情都会自动为您处理。