Django按分类展示文章报错404:分类查询匹配失败求助
解决Django分类文章列表的404问题
看起来你遇到的404问题主要是CategoryListView里的get_queryset函数参数错误,还有URL配置和模型查询的几个小问题,我帮你一步步梳理并修正:
核心错误点分析
- 参数匹配错误:你在
get_object_or_404里用了id=self.kwargs.get('category__name'),但你的URL里根本没传递category__name这个参数,而且id是整数类型,category__name是字符串,类型不匹配,导致Django找不到对应的分类,直接返回404。 - 模型名拼写错误:返回查询集时你写了
Posts.objects,但你的模型是Post(单数),这会导致后续的属性错误。 - 过滤条件错误:
Post模型里没有category_name字段,正确的过滤应该通过外键category关联到Category对象,而不是用不存在的字段。
修正后的代码示例
第一步:修正views.py
这里分两种情况,如果你想用分类ID(pk)作为URL参数,用下面的代码:
from django.views.generic import ListView from django.shortcuts import get_object_or_404 from .models import Post, Category class CategoryListView(ListView): model = Post template_name = 'posts/post_category.html' # 给模板里的查询集起个直观的名字,方便调用 context_object_name = 'posts' def get_queryset(self): # 从URL的kwargs里获取分类的pk category = get_object_or_404(Category, pk=self.kwargs.get('pk')) # 过滤出该分类下的所有文章 return Post.objects.filter(category=category) # 可选:把当前分类对象传到模板,方便显示分类名称 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['category'] = get_object_or_404(Category, pk=self.kwargs.get('pk')) return context
如果你想更友好的URL(用分类的slug),可以改成这样:
class CategoryListView(ListView): model = Post template_name = 'posts/post_category.html' context_object_name = 'posts' def get_queryset(self): category = get_object_or_404(Category, slug=self.kwargs.get('slug')) return Post.objects.filter(category=category) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['category'] = get_object_or_404(Category, slug=self.kwargs.get('slug')) return context
第二步:修正urls.py
如果用pk的URL配置:
from django.urls import path from .views import CategoryListView urlpatterns = [ # 其他页面的URL配置... path('category/<int:pk>/', CategoryListView.as_view(), name='post-category'), ]
如果用slug的URL配置(记得同步修改Category模型的get_absolute_url):
path('category/<slug:slug>/', CategoryListView.as_view(), name='post-category'),
第三步:同步修正Category模型的get_absolute_url
如果用slug的话,把这个方法改成:
def get_absolute_url(self): return reverse('post-category', kwargs={'slug': self.slug})
模板里的使用示例(post_category.html)
<h1>分类:{{ category.name }}</h1> {% for post in posts %} <article> <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2> <p>{{ post.content|truncatewords:30 }}</p> <small>作者:{{ post.author.username }} | 发布时间:{{ post.date|date:"Y-m-d H:i" }}</small> </article> {% empty %} <p>这个分类下还没有文章哦~</p> {% endfor %}
这样修改后,应该就能正常显示对应分类的文章了,不会再出现404错误啦。
内容的提问来源于stack exchange,提问作者codecodecode
相关产品推荐
相关产品推荐

