如何在每个用户添加新帖子时更新我的​​post_count?

时间:2016-03-27 12:56:51

标签: python django count

我创建了一个函数,并在用户添加帖子时在主视图中调用它。但是当我添加新帖子时,post_count没有更新,我收到了这个错误:

`type object 'Post' has no attribute 'post_count'

我做错了什么?

这是我的model.py

class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, )
    title = models.CharField(max_length=100)
    body = models.TextField()
    date = models.DateField(auto_now_add=True)
    likes = models.IntegerField(default=0)
    post_count = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.title

这是我的view.py:

def create_post(request):
    context = RequestContext(request)
    if request.method == 'POST':
        pform = PostForm(data=request.POST, prefix='PostForm')
        if pform.is_valid():

            new_post = pform.save(commit=False)
            new_post.user = request.user
            post_count(request, new_post.user)
            new_post.save()
            return HttpResponseRedirect('/forum/all')
    else:
        pform = PostForm()

    return render_to_response('forum/createpost.html',
                              {'pform': pform},
                              context)

这是我计算更新每位用户的帖子数量的函数。

def post_count(request, user, **kwargs):
        if user:
            Post.post_count += 1
            Post.save()

1 个答案:

答案 0 :(得分:0)

def post_count(request, user, **kwargs):
    if user:
        user.post_count += 1
        user.save()

将post对象传递给函数,然后更改对象的post_count,而不是类。

帖子上的post_count没有多大意义。你不是故意要对用户这么做吗?