1

我正在尝试显示相关帖子,相关性基于类别。Post 模型具有类别模型的外键。

有没有更好的方法来做到这一点。目前我正在使用会话从 single_post_detail_view 发送 category_name 到自定义 context_processor 函数,然后返回与该类别相关的帖子。

视图.py

class PostDetailView(DetailView):
    def get(self, request, slug):
        post = Post.objects.get(slug=self.kwargs['slug'])
        context = {
            'post' : post
        }
        request.session['category'] = post.category.name
        return render(request, 'blog/post_detail.html', context)

context_processors.py

from blog.models import Category

def related_posts(request):
    if request.session['category']:
        category = request.session['category']
    return {
        'related_posts': Category.objects.get(name=category).posts.all()
    }

然后在 HTML

{% for post in related_posts %}
   <a href="post.get_absolute_url()">{{post.title}}</a>
{% endfor %}
4

1 回答 1

1

上下文处理器旨在为每个请求运行。如果您需要向它传递信息,这表明您不应该使用上下文处理器。

您可以使用辅助功能,

def related_posts(category):
    return category.posts.all()

然后手动将帖子添加到视图中的上下文中:

    context = {
        'post': post,
        'related_posts': related_posts(post.category)
    }

或者您可以编写自定义模板标签。

一个简单的标签可以让你这样做:

{% related_posts post.category as related_posts %}
{% for post in related_posts %}
    ...
{% endfor %}

或者也许您可以使用包含标签来呈现链接:

{% related_posts post.category %}
于 2019-04-25T10:48:11.217 回答