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

Django登录功能失效求助:用户无法完成登录

Django登录功能失效的问题排查与修复

问题点分析

  • 请求方法判断错误:视图代码中request.method == 'post'使用了小写,Django中请求方法需用大写POST,导致表单提交后无法进入登录处理逻辑。
  • 函数命名冲突:视图函数命名为login,和从django.contrib.auth导入的系统login函数重名,会覆盖系统登录函数,导致调用异常。
  • 输入框类型不规范:HTML中用户名输入框使用了type="username",标准应为type="text",部分浏览器兼容但可能引发未知问题。

修正后的代码

views代码

from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect

def user_login(request):  # 重命名避免与系统函数冲突
    if request.method == 'POST':  # 改为大写POST
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/')
    return render(request, 'login.html')

HTML代码

<form method="post">
    {% csrf_token %}
    <input type="text" name="username">  <!-- 改为标准text类型 -->
    <input type="password" name="password">
    <input type="submit" name="submit">
</form>

URL代码

path('login/', views.user_login, name="login")  # 对应重命名后的视图函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:10:11