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

Django添加href链接时出现NoReverseMatch错误求助

Django URL反向解析错误修复

错误详情

报错信息:

Reverse for 'listing' with arguments '('',)' not found. 1 pattern(s) tried: ['listing/(?P<listing_id>[0-9]+)\Z']

错误触发代码(index.html):

<h2><a href="{% url 'listing' listing.id %}">{{auction.title}}</a></h2>

问题原因

在模板的{% for auction in auctions %}循环中,当前遍历的商品对象变量名是auction,但调用URL反向解析时误用了listing.id——listing变量在当前循环上下文里不存在,导致传入空值,不符合URL规则要求的数字类型listing_id参数,因此解析失败。

修复方案

将模板中的listing.id替换为auction.id,对应循环中的当前商品对象:

<h2><a href="{% url 'listing' auction.id %}">{{auction.title}}</a></h2>

相关代码参考

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("create", views.create_listing, name="create"),
    path("listing/<int:listing_id>", views.listing, name = "listing"),
]

views.py

def listing(request,listing_id):
    listing = AuctionItem.objects.get(id = listing_id)
    return render(request, "auctions/listing.html",{
        "listing":listing
    })

修复后的index.html循环部分

{% extends "auctions/layout.html" %}

{% block body %}
    <h2>Active Listings</h2>

    {% for auction in auctions %}
    <div class = "frame">
        <img src="{{auction.image}}" style= "width: 30vw;">
        <h2><a href="{% url 'listing' auction.id %}">{{auction.title}}</a></h2>
        <div id="text"><strong>Price:</strong> ${{auction.price}}</div>
        <div id="text"><strong>Description:</strong> {{auction.description}}</div>
        <div id="text"><strong>Category:</strong> {{auction.category}}</div><br>
        <div id="date">Created {{auction.date}}</div>
    </div>

        {% empty %}
        <li>No item.</li>
    {% endfor %}
{% endblock %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:45:56