0

there is a question that makes me feel annoyed,what i want to do is when i request the detail.html then the views of Post model will add 1 as the visit counts ,how to do it?thanks.

blog/models.py

class Post(models.Model):
   views = models.PositiveIntegerField(default=0)

blog/views.py

def detail(request):
    return render(request, 'blog/detail.html')
Penny Poon
  • 13
  • 3

1 Answers1

6

You could increment the views count this way:

def detail(request, post_id):
    post = Post.objects.get(id=post_id)
    post.views += 1
    post.save()
    return render(request, 'blog/detail.html', context={'post': post})

I assumed that since it is a detail view, you would receive an unique key to identify which post will be rendered (that can be done on urls.py)

dethos
  • 3,336
  • 1
  • 15
  • 15