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

Django HttpResponseRedirect跳转路径重复出现challenges前缀报错如何解决

问题原因
  • 你在HttpResponseRedirect中使用了相对路径"challenges/" + redirect_month,相对路径会基于当前请求的路径进行拼接。当你访问/challenges/<数字>触发重定向逻辑时,当前路径的父级是/challenges/,相对路径拼接后就会得到/challenges/challenges/<月份>的错误路径。
  • 你的根URL配置已经把challenges/前缀分配给了子应用的路由,子应用内部的路由不需要再加challenges/前缀,硬编码路径也很容易出现这类拼写、层级错误。
解决方法

方法1:修改为绝对路径(快速修复)

把重定向的路径前加斜杠,指定从网站根路径开始计算:

return HttpResponseRedirect("/challenges/" + redirect_month)

这样跳转后路径会直接拼接为/challenges/february,符合你的路由规则。

方法2:使用Django路由反向解析(推荐,避免硬编码)

这种方法不需要手动写路径,完全依靠Django的路由系统自动生成正确路径,后续修改路由前缀也不需要调整业务代码:

  1. 先给子应用的路由添加name标识:
    修改challenges/urls.py:
urlpatterns = [
    path("<int:month>", views.monthly_challenges_by_number),
    path("<str:month>", views.monthly_challenge, name="monthly-challenge"),
]
  1. 在视图中调用reverse函数生成正确的重定向路径:
    修改views.py的重定向逻辑:
from django.shortcuts import reverse

def monthly_challenges_by_number(request,month):
    months = list(monthly_challenges.keys())
    redirect_month = months[month-1]
    redirect_path = reverse("monthly-challenge", args=[redirect_month])
    return HttpResponseRedirect(redirect_path)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 07:30:02