I don't have as my parameter in the function in the view (I only have the request), how do I get the specific post
mike bra
I am trying to display the number of comments in the index page just like it is displayed in the posts page. However, my def index has no parameters.
For my post.html I can display the number of comments like this
#for single-post page
def post(request, slug):
post = get_object_or_404(Post, slug=slug)
comments_count = Comment.objects.filter(post=post).count()
context_dict = {
'comments_count':comments_count,
}
return render(request, 'main/post.html', context_dict)
in the template
{{comments_count}}
I want to do the same with my index page.
def index(request):
try:
sort = request.GET["sort"].strip()
sort_method = SortMethods[sort]
page = request.GET["page"].strip()
except KeyError:
sort_method = SortMethods.score
page = 1
if sort_method == SortMethods.date:
post_list = Post.objects.order_by("-pub_date")
else:
post_list = Post.objects.all()
post_list = sorted(post_list, key=lambda x: x.get_score(), reverse=True)
paginator = Paginator(post_list, 30)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
context = {
"posts": posts,
"pages": paginator.page_range,
"sort": sort_method.name,
}
return render(request, "main/index.html", context)
Selcuk
The easiest way is to add a method to count the annotations in the Post
model :
class Post(models.Model):
...
def comments_count(self):
return Comment.objects.filter(post=self).count()
Then use it in your template like:
{% for post in posts %}
{{ post.title }}: {{ post.comments_count }}
{% endfor %}