【发布时间】:2021-02-24 14:05:03
【问题描述】:
大家好!
我正在使用 Django 创建一个小型博客,其中有一个应用程序。碰巧我已经定义了博客的很大一部分,这是:
- 主页视图。
- 每个出版物类别的浏览量。
- 查看每个帖子
- 等等
既然我想添加“关于作者”视图,当它应该重定向到其各自的 HTML 模板时,Django 最终会将自己重定向到另一个模板,这会产生 NoReverseMatch 错误。
简化代码,就是:
views.py:
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post, Author, Category
class Home(ListView):
def get(self, request, *args, **kwargs):
context = {
'post': Post.objects.get(title='NamePost')
}
return render(request, 'PageWebApp/home.html', context)
class PostSimple(DetailView):
def get(self, request, slug_post, *args, **kwargs)
context = {
'post': Post.objects.filter(slug_post=slug_post)
}
return render(request, 'PageWebApp/page-simple.html', context)
class PostsCategory(DetailView):
def get(self, request, category, *args, **kwargs):
# View that shows each of the categories within the blog
context = {
'categories': Category.objects.get(category=category)
}
return render(request, 'PageWebApp/posts-category.html', context)
class AboutAuthor(DetailView):
def get(self, request, slug_autor, *args, **kwargs):
context = {
'author': Author.objects.get(slug_author=slug_author)
}
return render(request, 'PageWebApp/page-author.html', context)
urls.py
from django.contrib import admin
from django.urls import path
from PageWebApp import views
urlpatterns = [
path ('', views.Home.as_view (), name = 'home'),
# [Here are the URLs to the other project templates (they work fine)]
# Next the conflictive ones:
path ('posts- <category> /', views.PostsCategory.as_view (), name = 'posts-category'),
path ('<slug: slug_post> /', views.PostSimple.as_view (), name = 'page-simple'),
path ('about-<slug: slug_author> /', views.AboutAuthor.as_view (), name = 'page-author'),
]
我有一个名为“base.html”的模板,所有其他模板都继承了它。
在名为“home.html”的 Start 模板中,我们可以实现以下功能:
<! - HERE GO OTHER TAGS THAT REDIRECT TO OTHER URLS ->
<h4> <a href="{% url 'posts-category' categories.category %}"> See posts from {{categories.category}} </a> </h4>
<h4> <a href="{% url 'page-simple' post.slug_post %}> {{post.title}} </a> </h4>
<h4> <a href="{% url 'page-author' author.slug_author %}> By: {{author.name}} </a> </h4>
正如我之前提到的,当进入主窗口“home.html”时,我有一系列“a”标签,它们重定向到各种模板,但特别是当我选择转到 page-author.html 的 URL 时模板,出于某种原因,Django 解释它应该重定向到页面类别,它给了我描述的错误。
Reverse for 'posts-category' with arguments '('',)' not found. 1 pattern(s) tried: ['posts\\-(?P<category>[^/]+)/$']
我已经彻底检查了每个 HTML 模板,它们都正确地重定向到了相应的 URL。
提前感谢您的回复和 cmets。
【问题讨论】: