Sup*_*Cow 1 python django django-models django-views
我试图在数据库中将复选框的值保存为true或false.我必须使用一个模型.如果选中该框,则保存值"1".但是,如果未选中该框,则会收到错误消息:
Django Version: 1.9.4
Exception Type: IntegrityError
Exception Value: (1048, "Column 'completed' cannot be null")
Run Code Online (Sandbox Code Playgroud)
目前我的设置如下:
在models.py我有:
class myClass(models.Model):
completed = models.BooleanField(default=False, blank=True)
Run Code Online (Sandbox Code Playgroud)
在views.py我有:
def create_myClass(request):
completed = request.POST.get('completed')
toSave = models.myClass(completed=completed)
toSave.save()
Run Code Online (Sandbox Code Playgroud)
在HTML中我有:
<label class="col-md-5" for="completed"> Completed: </label>
<input id="completed" type="checkbox" name="completed">
Run Code Online (Sandbox Code Playgroud)
我试图在BooleanField中设置required = False,因为其他一些帖子建议但是然后得到错误:TypeError: __init__() got an unexpected keyword argument 'required'.
我还尝试在views.py中将'completed'设置为False,如:
if request.POST.get('completed', False ):
commpleted = False
Run Code Online (Sandbox Code Playgroud)
和
completed = request.POST.get('completed')
if completed == 'null':
commpleted = False
Run Code Online (Sandbox Code Playgroud)
但是没有工作(不确定我的语法是否正确?)
任何想法或建议都非常感谢!
您可以打印值request.POST以查看您在视图中获得的内容.
如果没有指定value的复选框HTML元素的属性,将在传递的默认值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'
Run Code Online (Sandbox Code Playgroud)
如果未选中该复选框,则不会传递任何内容,在这种情况下,您False将从上述语句中获取.
我建议您使用Django ModelForm,如果可以的话,大部分内容都会自动为您服务.