【问题标题】:Is there any way to pass value to custom context_processor function from view?有没有办法从视图中将值传递给自定义 context_processor 函数?
【发布时间】:2019-04-25 10:16:17
【问题描述】:

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

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

views.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 %}

【问题讨论】:

  • 你为什么要这样做?如果它依赖于视图中的某些东西,那么它绝对不应该是上下文处理器。为什么不直接在视图中,或者作为模板标签?
  • 因为很多页面都用到了相关的帖子。
  • 请注意,对于像DetailView 这样的通用视图,通常不应覆盖get。您最终会失去功能或重复代码。在您的情况下,我会编写一个简单的基于函数的视图def post_detail(request, slug):,或者使用DetailView 并覆盖get_context_data 而不是get 以将related_posts 添加到上下文中。
  • 事情似乎在我头上,谢谢大家。
  • 此外,如果category 不在会话中,您当前的上下文处理器将引发KeyError,然后如果category 未设置,Category.objects.get(...) 将引发错误。

标签: django related-content


【解决方案1】:

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

你可以使用辅助函数,

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

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

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

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

simple tag 会让你这样做:

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

或者您可以使用inclusion tag 来呈现链接:

{% related_posts post.category %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2019-10-29
    相关资源
    最近更新 更多