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
相关产品推荐
相关产品推荐

