我正在尝试将复选框的值保存为数据库中的 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 中将“已完成”设置为 False,例如:
if request.POST.get('completed', False ):
commpleted = False
和
completed = request.POST.get('completed')
if completed == 'null':
commpleted = False
但都不起作用(不确定我的语法是否正确?)
非常感谢任何想法或建议!
请您参考如下方法:
您可以打印 request.POST 的值以查看您在 View 中获得的内容。
如果您没有在复选框 HTML 元素中指定 value 属性,则在 POST 中传递的默认值为 on 如果复选框已选中。
在 View 中,您可以检查 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如果可以的话,大部分事情都会自动为您处理。
