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