Django向数据库写入数据时触发NOT NULL约束失败错误的问题求助
解决Django中
NOT NULL constraint failed: pages_login.password错误 Hey there, let's break down what's causing this issue and fix it step by step!
问题根源
你的about视图函数没有区分GET请求和POST请求,这就是问题的核心:
- 当你提交表单(POST请求)时,
request.POST里包含了你输入的username和password值,所以保存Login实例的操作能正常执行。 - 但当你直接访问
/about/(这是GET请求)时,request.POST.get('username')和request.POST.get('password')都会返回None。而你的Login模型中,username和password字段默认不允许为NULL,此时执行user_data.save()就会触发NOT NULL约束失败的错误。
修复后的代码
更新你的views.py,让它只在POST请求时处理数据保存,GET请求时仅渲染页面:
from django.shortcuts import render from .models import Login def index(request): index_context = { 'name': 'yahia', 'age': '20', } return render(request, 'pages/index.html', index_context) def about(request): # 仅在POST请求时处理表单数据 if request.method == 'POST': usernamee = request.POST.get('username') password = request.POST.get('password') # 增加基础校验,避免保存空值 if usernamee and password: user_data = Login(username=usernamee, password=password) user_data.save() # 无论GET还是POST请求,最后都渲染about页面 return render(request, 'pages/about.html')
额外说明
request.method == 'POST'的判断确保我们只在用户提交表单时才执行数据库写入操作,用户直接访问页面时不会触发保存逻辑。- 新增的
if usernamee and password校验可以防止用户提交空表单时再次触发约束错误,进一步提升代码的健壮性。
内容的提问来源于stack exchange,提问作者Yahia Omar
相关产品推荐
相关产品推荐

