how to display the number of views of an article with django

57 views
Skip to first unread message

JEAN MARLON MBAN

unread,
Dec 18, 2019, 10:25:33 AM12/18/19
to Django users
how to display the number of views of an article with django

Awa M. Kinason

unread,
Dec 18, 2019, 10:41:50 AM12/18/19
to Django users
First, add a column on the article Model named "views_count" 

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. 

Binoy U

unread,
Dec 18, 2019, 10:43:20 AM12/18/19
to Django users

Making the answer with the assumption that article is a modal.

You can add a field named count(PostiveIntegerField) and increment the count every time an article is viewed. I hope you have implemented article view as a DetailView or similar function view.

On Wednesday, December 18, 2019 at 4:25:33 PM UTC+1, JEAN MARLON MBAN wrote:

Awa M. Kinason

unread,
Dec 18, 2019, 10:45:36 AM12/18/19
to Django users
I have made some typo errors in typing: view_count, please just adjust that in the code. So it should be "view_count" anywhere i mistakenly wrote "views_count"


On Wednesday, December 18, 2019 at 4:25:33 PM UTC+1, JEAN MARLON MBAN wrote:
Reply all
Reply to author
Forward
0 new messages