fix django views counter

耗尽温柔 提交于 2019-12-08 09:31:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!