需要关于Django中重定向视图的帮助(新增)

bzzcjhmw  于 2022-12-24  发布在  Go
关注(0)|答案(3)|浏览(150)

我已经发布了一个与此标题相同的问题everyone can see it from this link
很遗憾,因为是我第一次提问,出现了一些格式错误,这个问题暂时关闭了,我已经编辑过了,重新提交了,但是我不知道需要多长时间,所以我还是重新提问吧。
我正在开发一个阅读小说的网络应用程序,目前我在使用url引导视图的某个部分卡住了。我使用Django作为后端,PostgreSQL作为数据库,HTML和bootrap作为前端。我将在下面发布我的代码:
This is my urls.py (from the project folder):

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

This is my urls.py (from the app folder):

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
    path('', views.home),
    path('book/<slug:book_slug>/<slug:chapter_slug>/', views.detail, name='detail'),    
    path('genre/<slug:category_slug>', views.category_detail, name='category_detail'),  
    path('book/<slug:book_slug>', views.book_detail, name='book_detail'),
    path('register/', views.register, name="register"),
    path('login/',auth_views.LoginView.as_view(template_name="app/login.html"), name="login"),
    path('logout/',auth_views.LogoutView.as_view(next_page='/'),name='logout'),
]

This is my models.py:

from django.db import models

# Create your models here.
class Category(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True, blank=True, editable=True)
    def __str__(self):
        return self.name
class Chapter(models.Model):
    chapter = models.Count
    chapter_name = models.CharField(max_length=100)
    book = models.ForeignKey('Book', on_delete=models.CASCADE, null=True, related_name = 'Books')
    detail = models.TextField()
    slug = models.SlugField(max_length=100, unique=True, blank=True, editable=True)
    def __str__(self):
        return self.chapter_name
class Book(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True, blank=True, editable=True)
    cover_image = models.ImageField(upload_to= 'images/', blank= True, null = True)
    author = models.CharField(max_length=100)
    summary = models.TextField()
    category = models.ForeignKey('Category', on_delete=models.CASCADE, null = True, related_name = 'books')
    #date = models.DateField(auto_now_add=True)
    recommended_book = models.BooleanField(default=False)
    recommended_book_hot = models.BooleanField(default=False)
    recommended_book_new = models.BooleanField(default=False)
    recommended_book_finish = models.BooleanField(default=False)
    def __str__(self):
        return self.title

My views.py:

from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .forms import RegistrationForm
from .models import Book, Category, Chapter
from gtts import gTTS
from django.urls import reverse
from django.shortcuts import get_object_or_404
# Create your views here.
def home(request):
    recommended_book = Book.objects.filter(recommended_book = True)
    recommended_book_hot = Book.objects.filter(recommended_book_hot = True)
    recommended_book_new = Book.objects.filter(recommended_book_new = True)
    recommended_book_finish = Book.objects.filter(recommended_book_finish = True)
    return render(request, 'app/home.html', {'recommended_book': recommended_book, 'recommended_book_hot': recommended_book_hot, 'recommended_book_new': recommended_book_new, 'recommended_book_finish': recommended_book_finish})
def detail(request, book_slug, chapter_slug):
    book = get_object_or_404(Chapter, book__slug = book_slug,slug = chapter_slug)
    title = book.slug
    return render(request, 'app/detail.html', {'detail': book, 'title':title})
def register(request):
    form = RegistrationForm()
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    return render(request, 'app/register.html', {'form': form})
def category_detail(request, category_slug):
    category = Category.objects.get(slug = category_slug)
    books = Category.objects.prefetch_related('books')
    return render(request, 'app/genre_detail.html', {'category':category})
def book_detail(request, book_slug):
    book = Book.objects.get(slug = book_slug)
    book_category = book.category.first()
    similar_books = Book.objects.filter(category__name__startswith = book_category)
    return render(request, 'app/book_detail.html', {'book': book, 'similar_books': similar_books, 'book_category': book_category})

With the configurations in urls.py, I have managed to go from homepage to a specific novel index page with the url: localhost:8000/book/book.slug then read a chapter using urL: localhost:8000/book/book.slug/chapter.slug , I then place an HTML link to go back to the index page in case I want to stop reading the chapter that goes like this:

<div class="container p-2">
                <a href="/ " class="text-dark">Home  </a>/
                <a href="{%url 'book_detail' title%}" class="text-dark">{{detail.book}}</a>/
                <a href="" class="text-dark">{{detail.chapter_name}}</a>
            </div>

这就是我遇到问题的地方,因为我想到的是,当点击链接时,链接将再次指向索引页面localhost:8000/book/book.slug。但实际发生的是,它显示了一个NoReveseMatch错误后,章节页面重新加载。
根据我在查看日志后的推断,视图Book_detail()应该有一个slug作为参数,例如'test'(小说名为"Test"的slug),但是参数显示了一个空白的'('',)',这使得链接无法指向Book_detail()。
有人知道我做错了什么吗?任何帮助或建议都是感激的
编辑1:NoReverseMatching错误已被修复,但现在点击url将返回一个DoesNotExist at book/chapter.slug错误。
编辑2:这个问题已经回答了,你可以在下面看到答案。

gwbalxhn

gwbalxhn1#

将此更改为:

<a href="{%url 'book_detail' book.slug %}" class="text-dark">{{detail.book}}</a>/
z5btuh9x

z5btuh9x2#

试试这个

<a href="{%url 'book_detail' book__slug.slug %}" class="text-dark">{{detail`.book}}</a>
km0tfn4u

km0tfn4u3#

有关DoesNotExist的问题已修复!
我发现通过在views.py中的detail()处添加另一个定义,如下所示:

def detail(request, book_slug, chapter_slug):
    book = get_object_or_404(Chapter, book__slug = book_slug,slug = chapter_slug)
    index = Book.objects.get(slug = book_slug)
    title = index.slug
    return render(request, 'app/detail.html', {'detail': book, 'title':title})

然后将其添加到HTML中,如下所示:

<div class="container p-2">
                <a href="/ " class="text-dark">Home  </a>/
                <a href="{%url 'book_detail' title%}" class="text-dark">{{detail.book}}</a>/
                <a href="" class="text-dark">{{detail.chapter_name}}</a>
            </div>

我现在可以返回到索引页面了!
谢谢大家的帮助和建议。我也意识到犯了很多笨拙的错误,其实也不是很难解决,只是我忽略了。

相关问题