You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:32:34