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

Django URL无法精准识别0、1、2整数参数问题求助

问题原因分析
  1. 重定向路径错误:num_page_view中使用HttpResponseRedirect(topic)是相对路径跳转,当访问/my_app/0时,浏览器会跳转到/my_app/0/index(而非预期的/my_app/index/),这个URL不存在,进而触发Django的APPEND_SLASH机制,重定向到/my_app/0/index/,最终匹配到<str:topic>/模式,topic为0/index,而articles字典中无此键,导致报错。
  2. 未导入Http404:news_view中抛出Http404但未导入该异常类,会导致NameError错误。
  3. 索引越界风险:未校验num是否在topics_list的合法索引范围内,若访问大于等于5的数字会直接崩溃。
解决方案

1. 修正视图代码(my_app/views.py)

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.urls import reverse  # 导入reverse生成正确URL

articles = {
    'index' : "Hello this is a view inside my_app",
    'simple' : 'simple views',
    'sports' : 'Sports Page',
    'finance' : 'Finance Page',
    'politics' : "Politics Page"
}

def news_view(request, topic) :
    try :
        return HttpResponse(articles[topic]) 
    except KeyError:  # 明确捕获KeyError,避免误捕其他异常
        raise Http404("404 GENERIC ERROR") 

def num_page_view(request, num):
    topics_list = list(articles.keys())
    # 校验数字是否在合法索引范围内
    if num < 0 or num >= len(topics_list):
        raise Http404("Invalid page number")
    topic = topics_list[num]
    # 使用reverse生成正确的目标URL,避免相对路径错误
    return HttpResponseRedirect(reverse('news_view', args=[topic]))

2. 修正URL配置(my_app/urls.py)

给news_view添加name参数,方便reverse调用生成URL:

from django.urls import path
from . import views

urlpatterns = [
    path('<int:num>', views.num_page_view),
    path('<str:topic>/', views.news_view, name='news_view'),  # 添加name参数
]

验证效果

  • 访问/my_app/0时,会正确匹配num_page_view,生成/my_app/index/的URL并跳转,最终显示index对应的内容。
  • 访问超出范围的数字(如5)会抛出404错误,避免程序崩溃。
  • 0、1、2等数字参数会正常触发跳转,不再出现URL自动添加斜杠的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:35:17