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

Django登录视图功能异常:MySQL账户无法登录问题求助

Django登录验证失败问题排查

问题描述

我正在完成Python编程证书的期末项目,遇到了Django视图相关问题。MySQL数据库已与Django成功连接,且通过MySQL手动创建了用户账户,但使用该账户凭据登录时,系统提示“凭据无效或不存在”。在代码中添加打印语句后,user输出为None,但username和password能正常打印出输入的内容。

相关代码

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Discount, Store
from django.contrib.auth import authenticate, login as auth_login
from django.contrib.auth.decorators import login_required
from .forms import DiscountForm
from django.contrib.auth.models import User

# Create your views here.
def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        print(username)
        password = request.POST.get('password')
        print(password)
        user = authenticate(request, username=username, password=password)
        print(user)
        if user is not None:
            auth_login(request, user)  # Use auth_login instead of login
            return redirect('discountList')
        else:
            return render(request, 'index.html', {'error': 'Invalid credentials'})

    return render(request, 'index.html')

排查与解决方法

  • 密码存储格式错误:直接在MySQL中创建用户时,密码是明文存储的,但Django默认使用PBKDF2算法加密密码,authenticate只识别加密后的密码。解决方式:放弃手动在MySQL建用户,改用Django命令创建:
    运行python manage.py shell打开Django shell,执行:

    from django.contrib.auth.models import User
    User.objects.create_user(username='你的用户名', password='你的密码')
    

    或者用python manage.py createsuperuser创建账户。

  • 表单字段不匹配:检查前端登录表单的输入框name属性,必须和代码中request.POST.get('username')、request.POST.get('password')的参数完全一致,避免拼写错误(比如写成user_name或pwd)。

  • 用户状态异常:Django的User模型有is_active字段,若该字段为False,authenticate会返回None。可在Django shell中检查并修复:

    user = User.objects.get(username='你的用户名')
    print(user.is_active)
    # 若为False,执行以下代码激活
    user.is_active = True
    user.save()
    
  • 用户模型配置问题:如果项目使用了自定义用户模型,需确保settings.py中配置了AUTH_USER_MODEL,且authenticate方法调用的是正确的用户模型。

内容的提问来源于stack exchange,提问作者abeCamelCase

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:22:17