问题
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?
回答1:
You cannot rely on sessions to store such permanent information because sessions
are temporary.
The easiest way would be to add an additional model:
class UserSeenPosts(models.Model):
user = models.ForeignKey(User, related_name='seen_posts')
post = models.ForeignKey(Post)
and then do something like this:
def post_detail(request, post_id):
post = Post.objects.get(id=post_id)
if not request.user.seen_posts.filter(post_id=post_id).exists():
print "adding"
post.views += 1
post.save()
UserSeenPosts.objects.create(user=request.user, post=post)
return render(request, 'blog/detail.html', {'Post': post})
Hope it helps!
回答2:
i want to edit Jahongir Rahmonov answer because it's not working for me the post_detail function:
def post_detail(request, post_id):
post = Post.objects.get(id=post_id)
if UserSeenPosts.objects.filter(post=post, user=request.user).exists():
pass
else:
post.views += 1
post.save()
UserSeenPosts.objects.create(user=request.user, post=post)
return render(request, 'blog/detail.html', {'Post': Post.objects.get(id=post_id)})
来源:https://stackoverflow.com/questions/46505239/fix-django-views-counter