我正在遵循有关简单Django Web应用程序here的Mozilla教程。我真的将使用它作为我从事涉及设备管理工作的网站的模板。因此,当尝试添加带有链接/catalog/models
的页面(型号是设备的部件号)时,出现以下错误。我觉得这可能只是我没有看到的小错误。抱歉,格式太糟糕了。
/catalog/models.py
:
from django.db import models
from django.urls import reverse
the URL patterns
import uuid
import datetime
class Book(models.Model):
"""Model representing a book (but not a specific copy of a book)"""
title = models.CharField(max_length = 200)
author = models.ForeignKey('Author', on_delete = models.SET_NULL, null = True)
# Foreign Key used because book can only have one author, but authors can have multiple books
# Author as a string rather than object because it hasn't been declared yet in the file.
summary = models.TextField(max_length = 1000, help_text = 'Enter brief descp. of book') #TextField for longer descp.
isbn = models.CharField('ISBN', max_length = 13, help_text = '13 character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
#ManyToManyField used because genre can contain many books. Books can cover many genres.
#Genre class has already been defined so we can specify the object above.
genre = models.ManyToManyField(Genre, help_text = 'Select genre for this book') #Genre capitalized, calling model up
def __str__(self):
"""String for representing the Model object."""
return self.title
def get_absolute_url(self):
"""returns the URL to access a detail record for this book."""
return reverse('book-detail', args=[str(self.id)])
class Model(models.Model):
model_number = models.CharField('Model Number', max_length = 50)
manufacturer = models.ForeignKey('Manufacturer', on_delete =
models.SET_NULL, null = True)
category = models.ForeignKey('Category', on_delete =
models.SET_NULL, null = True)
description = models.TextField(max_length = 1000, help_text =
"Enter brief description of product", null = True) #TextField for
longer descriptions
def __str__(self):
return f'{self.model_number}..........{self.description}'
def get_absolute_url(self):
#Returns the url to access a particular location instance
return reverse('model-detail', args=[str(self.id)])
``
/catalog/admin.py
:
from django.contrib import admin
# Register your models here.
from .models import Book, Model
admin.site.register(Book)
admin.site.register(Model)
`` /catalog/urls.py :
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('books/', views.BookListView.as_view(), name='books'),
path('book/<int:pk>', views.BookDetailView.as_view(), name='book-
detail'),
path('models/', views.ModelListView.as_view(), name='models'),
]
`` /catalog/views.py
from django.shortcuts import render #generates HTML fiels using a template and data
#from django.http import HttpResponse
from .models import Book, Author, BookInstance, Genre, Model, Item,
Category, Ownership, Manufacturer, Location #imports model classes to
access data in views
from django.views import generic
def index(request):
"""View function for home page of site."""
#Generate counts of some of the main objects
num_books = Book.objects.all().count()
num_instances = BookInstance.objects.all().count()
#Available books (status - 'a')
num_instances_available =
BookInstance.objects.filter(status__exact='a').count()
#The 'all()' is implied by default.
num_authors = Author.objects.count()
context = {
'num_books': num_books,
'num_instances': num_instances,
'num_instances_available': num_instances_available,
'num_authors': num_authors,
}
#Render the HTML template index.html with the data in the context
variable
return render(request, 'index.html', context=context)
class BookListView(generic.ListView):
model = Book
class BookDetailView(generic.DetailView):
model = Book
class ModelListView(generic.ListView):
model = Model
class ModelDetailView(generic.DetailView):
model = Model
`` /catalog/templates/base_generic.html :
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}<title>Local Library</title>{% endblock %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-
MCw98 / SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO“ crossorigin =” anonymous“>
<!-- Add additional CSS in static file -->
{% load static %}
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2">
{% block sidebar %}
<ul class="sidebar-nav">
<li><a href="{% url 'index' %}">Home</a></li>
<li><a href="{% url 'books' %}">All books</a></li>
<li><a href="{% url 'models' %}">All Equipment</a></li>
<li><a href="">All authors</a></li>
<li><a href="">Scan Equipment Out</a></li>
<li><a href="">Scan Equipment In</a></li>
<li><a href="">Search For Equipment</a></li>
</ul>
{% endblock %}
</div>
<div class="col-sm-10 ">
{% block content %}{% endblock %}
</div>
</div>
</div>
</body>
</html>
`` /catalog/templates/catalog/model_list.html :
{% extends "base_generic.html" %}
{% block content %}
<h1>Model list</h1>
{% if model_list %}
<ul>
{% for model in model_list %}
<li>
<a href="{{ model.get_absolute_url }}">{{ model.model_number }}</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>There is no equipment in the database</p>
{% endif %}
{% endblock %}
更多错误
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8080/catalog/models/
Django Version: 2.0.7
Python Version: 3.6.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'catalog.apps.CatalogConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /Users/jeremy/weston_geophysical_corp/database/weston/locallibrary/locallibrary/catalog/templates/base_generic.html, error at line 21
Reverse for 'models' not found. 'models' is not a valid view function or pattern name.
11 : <link rel="stylesheet" href="{% static 'css/styles.css' %}">
12 : </head>
13 : <body>
14 : <div class="container-fluid">
15 : <div class="row">
16 : <div class="col-sm-2">
17 : {% block sidebar %}
18 : <ul class="sidebar-nav">
19 : <li><a href="{% url 'index' %}">Home</a></li>
20 : <li><a href="{% url 'books' %}">All books</a></li>
21 : <li><a href=" {% url 'models' %} ">All Equipment</a></li>
22 : <li><a href="">All authors</a></li>
23 : <li><a href="">Scan Equipment Out</a></li>
24 : <li><a href="">Scan Equipment In</a></li>
25 : <li><a href="">Search For Equipment</a></li>
26 : </ul>
27 : {% endblock %}
28 : </div>
29 : <div class="col-sm-10 ">
30 : {% block content %}{% endblock %}
31 : </div>
Traceback:
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
158. response = self.process_exception_by_middleware(e, request)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
156. response = response.render()
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/response.py" in render
106. self.content = self.rendered_content
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/response.py" in rendered_content
83. content = template.render(context, self._request)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/backends/django.py" in render
61. return self.template.render(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render
175. return self._render(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in _render
167. return self.nodelist.render(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render
943. bit = node.render_annotated(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render_annotated
910. return self.render(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/loader_tags.py" in render
155. return compiled_parent._render(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in _render
167. return self.nodelist.render(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render
943. bit = node.render_annotated(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render_annotated
910. return self.render(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/loader_tags.py" in render
67. result = block.nodelist.render(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render
943. bit = node.render_annotated(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/base.py" in render_annotated
910. return self.render(context)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/template/defaulttags.py" in render
447. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/urls/base.py" in reverse
90. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Users/jeremy/anaconda/envs/py36/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
636. raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /catalog/models/
Exception Value: Reverse for 'models' not found. 'models' is not a valid view function or pattern name.
答案 0 :(得分:1)
该错误是从您的models.py的最后一行生成的:
return reverse('model-detail', args=[str(self.id)])
您没有与该反向功能匹配的URL(如书架)。 在您的网址中添加以下路径:
path('model/<int:pk>', views.ModelDetailView.as_view(), name='model-detail'),
一切正常。