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

如何让Django中hours_ahead函数对应的URL路径代码正常运行

问题分析与解决

你的核心问题出在URL配置上:path('time/plus/(\d{1,2})/', hours_ahead) 写法错误——Django的path()函数不支持正则表达式分组,它采用尖括号<>的路径转换器语法,正则分组是re_path()(旧版url())的专属用法。

两种修正方案

方案1:改用re_path()(兼容正则写法)

修改urls.py中的urlpatterns:

from django.urls import re_path
# 注意加r前缀表示原生字符串,结尾加$匹配URL结束
re_path(r'^time/plus/(\d{1,2})/$', hours_ahead)

同时确保hours_ahead函数接收两个参数(请求对象+捕获的小时数),示例代码:

from django.http import HttpResponse
import datetime

def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        return HttpResponse("无效的小时数")
    future_time = datetime.datetime.now() + datetime.timedelta(hours=offset)
    return HttpResponse(f"<html><body>{offset}小时后的时间:{future_time}</body></html>")

方案2:用path()的路径转换器(更简洁)

如果坚持用path(),把正则分组换成路径转换器:

path('time/plus/<int:offset>/', hours_ahead)

int:会自动捕获数字并转为整数,直接传入hours_ahead的offset参数,函数定义和上面一致即可。

额外检查项

  • 确认hours_ahead函数已正确导入到urls.py中
  • 测试时访问类似http://你的域名/time/plus/3/的URL,验证是否正常返回结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:55:37