I am creating a blog using Django, and I want to count the views for each post. I call this function when a user reads the blog post:
def post_detail(request, post_id):
if 'viewed_post_%s' % post_id in request.session:
pass
else:
print "adding"
add_view = Post.objects.get(id=post_id)
add_view.views += 1
add_view.save()
request.session['viewed_post_%s' % post_id] = True
return render(request, 'blog/detail.html', {'Post': Post.objects.get(id=post_id)})
The problem is that when logging out and logging in again, the post views increase again. So why does django delete the sessions when the user logs out and how can I fix this?
i want to edit Jahongir Rahmonov answer because it's not working for me the post_detail function:
You cannot rely on sessions to store such permanent information because
sessions
are temporary.The easiest way would be to add an additional model:
and then do something like this:
Hope it helps!