计数视图有时有效,有时不计数

时间:2019-06-10 14:52:29

标签: python django

这很奇怪。有时很重要,有时却没有。我没有发现代码有什么问题,这是我的代码。

class Post(models.Model):
    with_votes = PostVoteCountManager() #nothing to do with views
    objects = models.Manager() #nothing to do with views
    views = models.PositiveIntegerField(default=0)


    @property
    def update_view(self):
        self.views = self.views + 1
        return self.save()

在我的html中,我只是做了

 <small class="text-muted ">{{ post.views }}view{{ post.views|pluralize }} | </small><span>

我的views.py

class PostDetailView(DetailView):
    model = Post


class PostListByMostViewedView(ListView):
    model = Post
    template_name = 'community/mostviewed_home.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-views']
    paginate_by = 5

2 个答案:

答案 0 :(得分:0)

  

我建议您制作一个detail_post视图并在其中编写逻辑   views.py以增加视图。

     

例如:

post = Post.objects.get(id=id)
post.views += 1
post.save()
  

如果您正在使用基于类的视图,请尝试

class PostDetailView(DetailView):
    model = Post

    def get(self, **kwargs):
        self.object.count += 1
        self.object.save()
        return super(PostDetailView, self).get(**kwargs)

答案 1 :(得分:0)

您认为您需要致电update_view。如果您不执行,则实例的view属性将不会更新。 例如,基于功能的视图:

def your_view(request, post_id):
    post = Post.objects.get(pk=post_id)
    post.update_view()
    context={'post': post}
    return render(request, 'your_template.html', context)

对于基于类的视图,您可以:

class YourView(View):

    model = Post

    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)
        post = context['post']
        post.update_view()
        context['post'] = post

        return context