You need to enable JavaScript to run this app. MDN Django LocalLibrary教程添加数据后报NoReverseMatch如何解决
优惠活动
大模型
产品
解决方案
定价
更多

MDN Django LocalLibrary教程添加数据后报NoReverseMatch如何解决

问题1:NoReverseMatch报错解决

你在catalog/urls.py中声明了app_name = 'catalog',开启了应用URL命名空间,所有反向解析该应用下的URL都需要带上catalog:前缀,修改两处模型代码即可:

  1. 修改Book模型的get_absolute_url方法:
def get_absolute_url(self):
    """Returns the url to access a detail record for this book."""
    return reverse('catalog:book-detail', kwargs= {'pk': self.id})
  1. 修改Author模型的get_absolute_url方法:
def get_absolute_url(self):
    from django.urls import reverse
    """Returns the url to access a particular author instance."""
    return reverse('catalog:author-detail', args=[str(self.id)])

问题2:book_list.html模板变量错误

模板中你写了{{ author.get_absolute_url }},但循环上下文里只有book变量,没有单独的author变量,修改为:

<a href="{{ book.author.get_absolute_url }}">({{ book.author }})</a>

问题3:base.html加载报错解决

检查base.html顶部是否添加了静态文件加载标签,放在文件第一行即可:

{% load static %}

所有bootstrap的CSS、JS引用都要使用静态模板标签写法,示例:

<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

其他可选修复(不影响当前报错,但会导致功能异常)

views.py中index函数的可用图书统计条件写错,你定义的LOAN_STATUS里可用状态是a,不是avail,修改为:

num_instances_available = BookInstance.objects.filter(status__exact='a').count()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 16:15:07