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

Django HttpResponseRedirect重定向路径错误,请求修复帮助

修复Django重定向路径错误问题

你遇到的问题是相对路径解析逻辑导致的:当访问mydomain.com/my_app/0/时,当前请求URL末尾带有斜杠,浏览器会把HttpResponseRedirect(topic)中的topic解析为当前路径的子路径,最终跳转到mydomain.com/my_app/0/finance,而非预期的mydomain.com/my_app/finance。

下面提供两种修复方案,推荐使用第二种更规范的方式:

方案1:使用绝对路径前缀

直接在重定向目标路径前添加应用URL前缀(比如/my_app/),确保路径相对于域名根目录:

修改视图中的num_page_view函数:

def num_page_view(request, num_page):
    topics_list = list(articles.keys())
    # 处理页码越界,避免报错
    if num_page >= len(topics_list):
        raise Http404("Invalid page number")
    topic = topics_list[num_page]
    # 添加应用前缀的绝对路径
    return HttpResponseRedirect(f'/my_app/{topic}/')

方案2:使用URL反转(推荐)

通过Django的reverse函数根据URL名称生成正确路径,避免硬编码路径,适配后续URL结构变更:

步骤1:给URL配置添加名称

修改urls.py,为每个URL规则添加name参数:

from django.urls import path
from . import views
urlpatterns = [
    path('<int:num_page>/', views.num_page_view, name='num-page'),
    path('<str:topic>/', views.news_view, name='news-topic')
]

步骤2:在视图中用reverse生成路径

修改views.py,导入reverse并替换原重定向代码:

from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseRedirect 
from django.urls import reverse  # 新增导入

articles = {
    'finance' : 'finance page',
    'sports' : 'sports page'
}

def news_view (request,topic):
    return HttpResponse(articles[topic])

def num_page_view(request,num_page):
    topics_list = list(articles.keys())
    # 处理页码超出范围的情况
    if num_page >= len(topics_list):
        raise Http404("Invalid page number")
    topic = topics_list[num_page]
    # 根据URL名称反转生成正确路径
    return HttpResponseRedirect(reverse('news-topic', kwargs={'topic': topic}))

修改后,访问mydomain.com/my_app/0/就会正确跳转到mydomain.com/my_app/finance/。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:52:38