简体   繁体   中英

Is there any way to pass value to custom context_processor function from view?

I am trying to show related posts, relatedness is based on category. Post model has a foreign key to category model.

Is there any better way of doing this. Currently I am sending category_name from single_post_detail_view using the session to custom context_processor function, which then returns the posts related to that category.

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()
    }

and then in HTML

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

A context processor is meant to run for every request. If you need to pass information to it, it's a sign that you shouldn't be using a context processor.

You could use a helper function,

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

then manually add the posts to the context in the view:

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

Or you could write a custom template tag.

A simple tag would let you do:

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

Or perhaps you could use an inclusion tag to render the links:

{% related_posts post.category %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM