First, add a column on the article Model named "views_count"
On Wednesday, December 18, 2019 at 4:25:33 PM UTC+1, JEAN MARLON MBAN wrote:
-- Then on the DetailView of the article, and on the GET method. add this:
<code>
article.view_count += 1
article.save()
# or (asuuming you are using class based views)
self.object.view_count += 1
self.object.save()
</code>
The problem with this method is that view_count will be updated each time the same person routes to that view or refreshes the page. To avoid this, you can add a list of
counted articles in session. Something like
<code>
if 'counted_articles' not in session:
session['counted_articles'] = []
# new line
if self.object.id not in session['counted_articles']:
session['counted_articles'].append(self.object.id)
self.object.views_count += 1
self.object.save()
</code>
This will ensure that for each session, the article is counted only once.
hope that helps, if you have any questions, feel free to post them below.
On Wednesday, December 18, 2019 at 4:25:33 PM UTC+1, JEAN MARLON MBAN wrote:
how to display the number of views of an article with django
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/06d9c91a-a83e-45da-8c60-dc2380c216e9%40googlegroups.com.
No comments:
Post a Comment