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

Django自定义用户登录视图无法重定向至首页问题求助

Django登录后无法重定向至Home页面的问题修复

核心问题分析

终端返回200状态码说明登录请求被正常处理但未触发重定向,根本原因是注册时用户密码未正确哈希存储,导致authenticate()无法验证通过,始终返回None,因此不会执行重定向逻辑,停留在登录页。此外还存在URL命名空间不匹配的小问题,需一并修正。

分步修复方案

1. 修复注册视图的用户创建逻辑

signup视图中直接用表单实例化用户并保存的方式错误,未对密码进行哈希处理。修改views.py中的signup函数:

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            # 创建用户实例但暂不保存
            user = form.save(commit=False)
            # 对密码进行哈希处理
            user.set_password(form.cleaned_data['password'])
            user.save()
            return redirect('login')

    else:
        form = SignUpForm()   
    return render(request, 'signup.html', {'form': form})

2. 修正登录视图的重定向命名空间

你的URL配置未设置命名空间backend_,因此登录视图中的重定向应直接使用URL名称home,修改views.py中的log_in函数:

def log_in(request):
    if request.method == 'POST':
        form = LogInForm(request.POST)
        if not form.is_valid():
            print("Form errors:", form.errors)
            messages.error(request, '邮箱或密码格式错误')
        else:
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            
            user = authenticate(request, email=email, password=password)
            if user is not None:
                login(request, user)
                messages.success(request, '登录成功')
                return redirect('home')
            else:
                messages.error(request, '邮箱或密码错误')
    else:
        form = LogInForm()
    return render(request, 'login.html', {'form': form})

同时修正log_out视图的重定向,使用URL名称更规范:

def log_out(request):
    logout(request)
    messages.success(request, '再见!')
    return redirect('home')

3. 模板中的URL命名空间修正

home.html中所有{% url %}标签里的backend_:前缀需去掉,因为你的URL配置未设置命名空间:

{% extends 'base.html' %}
{% block content %}

{% if request.user.is_authenticated %}

  你已登录,欢迎 {{ request.user.username }}!

  <p><a href="{% url 'logout' %}">退出登录</a></p>

{% else %}
  <p>你尚未登录</p>
  <a href="{% url 'login' %}">登录</a> |
  <a href="{% url 'signup' %}">注册</a>

{% endif %}

{% endblock %}

验证修复效果

  1. 重新创建测试用户,此时密码会被正确哈希存储
  2. 使用该用户登录,终端会返回302重定向状态码,成功跳转至home页面
  3. home页面会显示用户已登录的状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:53:13