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,
then manually add the posts to the context in the view:
Or you could write a custom template tag.
A simple tag would let you do:
Or perhaps you could use an inclusion tag to render the links: