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

Django中HttpResponseRedirect不生效:未登录提交评论无法跳转至登录页

问题描述

我在实现listing(request, listId)函数时遇到一个问题:当未登录用户提交评论时,期望自动跳转至登录页,但点击提交按钮后页面没有跳转,仍停留在原页面。我已经尝试过HttpResponseRedirect(reverse("login"))、redirect("login")以及直接指定URL的方式,都没能解决问题。

相关代码如下:

views.py

def listing(request, listId):

    if request.method == "POST":

        if request.user.is_authenticated:
            
            # some code here to manipulate data
        else:
            HttpResponseRedirect(reverse("login"))


    return render(request, "auctions/listing.html", 
                    {
                      "listing":Listing.objects.get(pk=listId),
                      "comments": Listing.objects.get(pk=listId).itemComment.all(),
                      "bids": Listing.objects.get(pk=listId).itemBid.all(),
                      "bidCount": Listing.objects.get(pk=listId).itemBid.count(),
                      "currentPrice": currentPrice,
                      "isValidBid": True
                      }
                  )

urls.py

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("add_listing", views.addListing, name="addListing"),
    path("listing_<int:listId>", views.listing, name="listing")
]
问题根源

你的代码逻辑有个关键错误:在else分支中,你只是创建了HttpResponseRedirect对象,但没有将其返回。函数会继续执行到末尾的return render(...)语句,最终返回的是渲染后的列表页面,而非跳转响应,所以页面不会发生跳转。

修复方案

修改views.py中的listing函数,在else分支里添加return语句,返回跳转响应:

from django.shortcuts import redirect, render, get_object_or_404
from .models import Listing

def listing(request, listId):
    # 提前查询Listing对象,避免重复查询数据库,同时处理对象不存在的情况
    listing_obj = get_object_or_404(Listing, pk=listId)
    # 确保currentPrice变量已正确定义
    currentPrice = # 此处补充你的currentPrice计算逻辑

    if request.method == "POST":
        if request.user.is_authenticated:
            # 处理已登录用户的评论提交逻辑
            # some code here to manipulate data
        else:
            # 添加return返回跳转响应,使用redirect快捷函数更简洁
            return redirect("login")

    return render(request, "auctions/listing.html", 
                    {
                      "listing": listing_obj,
                      "comments": listing_obj.itemComment.all(),
                      "bids": listing_obj.itemBid.all(),
                      "bidCount": listing_obj.itemBid.count(),
                      "currentPrice": currentPrice,
                      "isValidBid": True
                      }
                  )
额外优化点
  1. 减少数据库查询:原代码多次调用Listing.objects.get(pk=listId),会重复访问数据库,提前查询一次并复用变量能提升性能。
  2. 异常处理:使用get_object_or_404替代直接get,当指定id的Listing不存在时,会返回友好的404页面,避免抛出未处理的异常。
  3. 代码简洁性:Django的redirect快捷函数支持直接传入URL名称(如redirect("login")),无需手动调用reverse,代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:05:06