【发布时间】:2022-01-19 22:25:24
【问题描述】:
我无法显示类别/给定类别的可路由索引页面。
我的代码使用: -BlogCategory(模型)
-BlogPageBlogCategory(页面)一个中间结构,链接到:
-PostPage(页面)
我可以将代码传递给 post_page 模板,但是当我单击特定类别链接时,我得到:
Reverse for 'post_by_category' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P<category>[-\\w]+)/$']
@gasman 在下面的帖子中写道:“routeablepageurl 标签收到了一个空字符串”。我找不到“空”字符串/缺少的链接。
我认为这与我的“def post_by_category”的路线有关。任何有助于我加深学习的意见都会很棒。
NB - 如果它有帮助,当我在没有中间页面的情况下运行此过程时,一切都很好。单击 PostPage 中的类别后,我可以显示 BlogPage/given_category。
这是我的代码:
型号
class BlogPage(RoutablePageMixin, Page):
...
def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
context["posts"] = posts
return context
def get_posts(self):
return PostPage.objects.descendant_of(self).live().order_by("-post_date")
@route(r'^category/(?P<category>[-\w]+)/$')
def post_by_category(self, request, category, *args, **kwargs):
self.posts = self.get_posts().filter(categories__blog_category__slug=category)
context["categories"] = BlogCategory.objects.all()
return self.render(request)
class PostPage(MetadataPageMixin, Page):
...
content_panels = Page.content_panels + [
...
InlinePanel("categories", label="category"),
...
def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
return context
class PostPageBlogCategory(models.Model):
page = ParentalKey(
"blog.PostPage", on_delete=models.CASCADE, related_name="categories"
)
blog_category = models.ForeignKey(
"blog.BlogCategory", on_delete=models.CASCADE, related_name="post_pages"
)
panels = [
SnippetChooserPanel("blog_category"),
]
class Meta:
unique_together = ("page", "blog_category")
@register_snippet
class BlogCategory(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(unique=True, max_length=80)
panels = [
FieldPanel('name'),
FieldPanel("slug"),
]
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'categories'
post_page.html:
{% extends "base.html" %}
{% load wagtailroutablepage_tags %}
...
{% for category in page.categories.all %}
<li>
<a href="{% routablepageurl blog_page "post_by_category" category.slug %}">
{{ blog_category.name }}
</a>
</li>
{% empty %}
No categories yet'
{% endfor %}
...
【问题讨论】:
-
我建议您从 post_page.html 模板中删除
{% routablepageurl %}标签开始调试,并直接输出{{ category.slug }}。如果 - 正如我所怀疑的 - 它是一个空字符串,那么您有一个与 RoutablePage 无关的错误需要调查。
标签: django-models routes wagtail