我在获取Novel网页以返回特定书的适当章节的视图时遇到麻烦。我的索引页面列出了Book模型类的所有对象,并将它们超链接到带有Slug字段的详细信息页面。
<li><a href="{% url 'bible:detail' book.slug %}">{{ book.name }}</a></li>
这应该使用slug参数(正确???)调用我的detail.html页面。详细信息视图与Chapter模型类一起使用,该章模型类通过外键(ID号)链接到Book模型类。我意识到Chapter模型类没有自己的子域,但我认为它应该能够通过与书籍模型的关系来映射url。这是一个错误的假设吗?我知道我可以将slug字段添加到章节模型中,但是由于应用程序是翻译器,因此似乎很多余,我最终将为每个章节中的句子创建一个模型类。我该如何工作? 我不知道我的方法是否正确,但这是我得到的错误:
TypeError at /novel/1984/
get_queryset() missing 2 required positional arguments: 'request' and 'slug'
模型由外键(在Book中)链接的2个类(Book和Chapter)组成。书籍索引页面列出了图书馆中的每本书籍,并列出了其章节索引页面的超链接。书籍索引页面可以正常工作,但是我似乎无法正确地将参数传递给章节视图并显示章节索引页面(只需列出章节编号,稍后我也将对其进行超链接)。该代码有些怪异,如果不需要任何东西,或者有更简单的方法请告知。任何帮助将不胜感激
models.py
from django.db import models
from django.template.defaultfilters import slugify
class Book(models.Model):
number = models.PositiveIntegerField(primary_key=True, unique=True, db_index=True)
name = models.CharField(max_length=33, db_index=True)
short = models.CharField(max_length=7)
search = models.CharField(max_length=7)
chaptercount = models.IntegerField()
title = models.CharField(max_length=33)
slug = models.SlugField(max_length=33, verbose_name=('Book Slug'), default=name)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Book, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Meta:
ordering = ['number',]
class Chapter(models.Model):
book = models.ForeignKey(Book, related_name='chapters', on_delete=models.CASCADE)
number = models.PositiveIntegerField(db_index=True)
def __str__(self):
return '%s %s' % (self.book.slug, self.number)
def get_absolute_url(self):
return ('chapter_detail', [self.book.slug, self.number])
class Meta:
ordering = ['number',]
unique_together=(('book','number',),)
urls.py
from django.urls import path
from django.conf.urls import url
from . import views
app_name = 'novel'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<slug:book_slug>/', views.BooklistView.as_view(), name='detail'),
]
views.py
from django.urls import reverse
from django.views.generic import ListView, DetailView, UpdateView
from django.shortcuts import get_object_or_404
from .models import Book, Chapter
class IndexView(ListView):
template_name = 'novel/index.html'
context_object_name = 'lib_books'
def get_queryset(self):
return Book.objects.all()
class BooklistView(ListView):
template_name = 'novel/detail.html'
context_object_name = 'book_chapters'
def get_queryset(self, request, slug):
return Chapter.objects.filter(slug=book_slug)
index.html
{% if lib_books %}
<ul>
{% for book in lib_books %}
<li><a href="{% url 'novel:detail' book.slug %}">{{ book.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No page available.</p>
{% endif %}
bookdetail.html
{% if book_chapters %}
<ul>
{{ chapter.book.title }} {{ book.number }} Chapters
{% for chapter in book_chapters %}
<li>{{ chapter.number }}</li>
{% endfor %}
</ul>
{% else %}
<p>No page available.</p>
{% endif %}