In views.py ### category_posts = Post.objects.filter(categor



我正在django中创建一个博客应用程序,在那里我遇到了这个不寻常的问题。我不能过滤和显示博客帖子分类明智。请找到我的代码下面。提前谢谢。

MODELS.py

这是我为一篇博文创建的模型。

class Post(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default="uncategorized")
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
#return reverse('article-detail', args=(str(self.id)))
return reverse('homepage')

VIEWS.py

这是我为分类博客文章创建的视图。

def CategoryView(request,cats):
category_posts = Post.objects.filter(author= 'apaar')
return render(request,'categories.html',{'cat':cat,'category_posts':category_posts})

urls . py

url .py文件

path('category/<str:cat>/', CategoryView, name = 'category'),

CATEGORIES.html

这将是category_posts作为空查询集显示的最后一个显示页面。for循环无法运行,因为category_posts是一个空查询集。

{% extends 'base.html' %}
{% load static %}
{% block content %}
<h1>Categories</h1>
<ul>
{% for posts in category_posts %}
<li>
<div class="category"><a href="{% url 'category' post.category|slugify %}">{{ post.category }}</a></div>
<a href="{% url 'article-detail' post.pk  %}"><h3><b>{{ post.title }} </b></h3>
<p class=card-date>    <big>{{ post.author }}</big><small> -{{ post.post_date }}     </small> </p>
<p class="excerpt-text">{{ post.body | slice:"100" |safe}}</p>
<div class="article-thumbnail">
<img src="{% static "images/bg.png" %}" alt="article-thumbnail" >
<div class="overlay"></a>
</li>
{% endfor %}
{% endblock %}

根据我的理解,你想要做的是:

def CategoryView(request,cat):
category_posts = Post.objects.filter(category=cat)
return render(request,'categories.html',{'category_posts':category_posts})

使用cat作为你的参数,因为你在url .py中使用<str:cat>,否则你可能会得到一个"意外参数";错误。
你必须过滤category,而不是author。你的问题是正确的,但你的代码不是。
您不需要在上下文中传递cat变量,因为任何帖子都会在其自身中包含它。

接受@Willem Van Onsem和@Roham的建议:

{% for post in category_posts %}
# ...
<div class="category"><a href="{% url 'category' post.category    %}">{{ post.category }}</a></div>

如果你想使用slugs,也许签出models.SlugField

最新更新