修复Django意见计数器 [英] fix django views counter

查看:45
本文介绍了修复Django意见计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django 创建博客,并且希望计算每个帖子的观看次数.当用户阅读博客文章时,我将调用此函数:

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

问题在于,注销并再次登录时,帖子视图会再次增加.那么,django为什么在用户注销时删除会话,我该如何解决?

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?

推荐答案

您不能依靠会话来存储此类永久信息,因为 sessions 是临时的.

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)

然后执行以下操作:

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

希望有帮助!

这篇关于修复Django意见计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆