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

在Django的HTML文件中使用URL模式时出现NoReverseMatch错误求助

Django NoReverseMatch 问题解决:正确使用{% url %}标签传递参数

你在模板里的{% url %}标签写法完全错了——不能把模板变量用{{}}嵌套在标签内部的视图名称里,这会让Django把整个拼接后的字符串当成视图名称去匹配,自然找不到对应的URL模式。

错误根源

你的URL配置里视图名称是add_to_trip,但你写的模板代码把add_to_trip/{{trip_id}}/{{place_results_name}}/{{place_results_addr}}/{{place_results_rating}}当成了视图名称,这显然和配置里的name="add_to_trip"不匹配,直接触发了NoReverseMatch错误。

正确的模板写法

把参数直接作为位置参数或者关键字参数传给{% url %}标签即可:

位置参数写法(按URL里的参数顺序传递)

<a class="btn btn-primary" href="{% url 'add_to_trip' trip_id place_results_name place_results_addr place_results_rating %}" style="margin-top: 10px;">Add to trip</a>

关键字参数写法(更清晰,不易出错)

<a class="btn btn-primary" href="{% url 'add_to_trip' id=trip_id name=place_results_name addr=place_results_addr rating=place_results_rating %}" style="margin-top: 10px;">Add to trip</a>

额外注意点

  • 确保模板中的trip_id是整数类型,place_results_name、place_results_addr、place_results_rating是字符串类型(如果rating是浮点数,Django会自动转换为字符串适配URL的str类型要求)。
  • 关键字参数的名称必须和URL配置里的参数名完全一致:id、name、addr、rating,不能写错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:22:50