我是否缺少一些简单的东西? NoReverseMatch只在/用于首页/索引

时间:2018-10-13 18:17:05

标签: python django

当我尝试仅访问首页(即NoReverseMatch at /)时,出现以下localhost:8000错误。

如果我转到localhost/books/<slug>,则没有错误,并且页面按预期显示。

NoReverseMatch位于/

Reverse for 'book_detail' not found. 'book_detail' is not a valid view function or pattern name.
Request Method: GET
Request URL:    http://localhost:8000/
Django Version: 2.1.2
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'book_detail' not found. 'book_detail' is not a valid view function or pattern name.

模板渲染期间发生错误

In template D:\Documents\django\myproject\library\templates\base.html, error at line 10

Reverse for 'book_detail' not found. 'book_detail' is not a valid view function or pattern name.

base.html的第10行在哪里:

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

以下是相关代码:

urls.py

from django.contrib import admin
from django.urls import path

from library import views

urlpatterns = [
    path('', views.index, name='home'),
    path('books/<slug>/', views.book_detail, name='book_detail'),
    path('admin/', admin.site.urls),
]

views.py

from django.shortcuts import render
from library.models import Book

def index(request):
    books = Book.objects.all()
    return render(request, 'index.html', {
        'books': books,
    })

def book_detail(request, slug):
    book = Book.objects.get(slug=slug)
    return render(request, 'books/book_detail.html', {
        'book': book,
    })

models.py

from django.db import models

class Book(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    slug = models.SlugField(unique=True)

index.html

{% block content %}
    <h1>Hello World!</h1>
    {% for i in books %}
      <a href="{% url 'book_detail' slug=book.slug %}">
        <h2>{{ i.name }}</h2>
      </a>
      <p>{{ i.description }}</p>
    {% endfor %}
{% endblock content %}

即使我将urls.pyviews.py和html文件中的book_detail的所有实例都注释掉了,我在localhost:8000上也得到了相同的错误消息。

我认为我缺少一些非常简单的东西。其他人以前似乎曾遇到过此问题,但他们使用的是较早的django和RegEx,但我似乎无法自行解决。

我将不胜感激!

0 个答案:

没有答案