7

I am performing a Blog application using Django. I want to track the count of the page view whenever a user sees a particular blog, whether it is a registered user or non-registered users. And I also want to display the most viewed blogs according to the view count.

Can anyone help me out in this? Thank you.

Salek
  • 449
  • 1
  • 10
  • 19
Niladry Kar
  • 1,163
  • 4
  • 20
  • 50
  • For non-registered users - just leverage Google Analytics. I imagine for users who login, you may be able to use funnels an stuff and figure all of this out via analytics. That won't help with displaying based on view count, but you didn't give us any code to work with. – Hanny Sep 20 '18 at 13:05
  • you can use middleware...But i don't have your code and your project hierarchy – Mbambadev Sep 20 '18 at 13:05

3 Answers3

15

models.py

class Blog(models.Model):
    #fields you need
    blog_views=models.IntegerField(default=0)

views.py

def blog_post(request,post_id):
    #your code
    blog_object=Blog.objects.get(id=post_id)
    blog_object.blog_views=blog_object.blog_views+1
    blog_object.save()
    #your code

This will simply count each blog visits. This will also count multiple views by a single user.

Abhijith Konnayil
  • 4,067
  • 6
  • 23
  • 49
  • 5
    `blog_views = blog_views + 1` introduces a race condition. Consider the case when the server processes multiple requests in parallel and an update occurs between `get()` and `save()`. A better approach uses `F()` expressions, see [this answer](https://stackoverflow.com/questions/1598932/atomic-increment-of-a-counter-in-django) – sauerburger Jan 08 '21 at 12:45
7

We can count views using IPAdress by creating a table for post views in the database.

In models.py

from django.contrib.auth.models import User
class PostViews(models.Model):
    IPAddres= models.GenericIPAddressField(default="45.243.82.169")
    post = models.ForeignKey('Post', on_delete=models.CASCADE)

    def __str__(self):
        return '{0} in {1} post'.format(self.IPAddres,self.post.title)

Then, make it a property to the Post class like that.

models.py for example:

class Post(models.Model):
    title = models.CharField(max_length=100, unique= True)
    slug= models.SlugField(blank=True, null=True, unique=True)
    @property
    def views_count(self):
        return PostViews.objects.filter(post=self).count()

you can read about property here then

In views.py

from .models import PostViews

def PostsDetailsView(request,slug):
    post_details=Post.objects.get(slug=slug)
    def get_client_ip(request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    PostViews.objects.get_or_create(user=request.user, post=post_details)

So this function ensures that if this IPAdress has seen this post it will do nothing if he sees the post for the first time it will create an object in the database and count it as a view. You can read more about IPAdress here. Don't forget to make migrations, migrate and register PostViews class in admin.py

Lars
  • 1,234
  • 1
  • 8
  • 31
1
  1. Add IntegerField to your Model for storing count of views.
  2. Change your view so, it will increase the count by adding one to previous count when view gets request.

models.py:

blog_view = models.IntegerField(default=0)

views.py:

class BlogView(DetailView):
    model = Blog
    def get_object(self):
        obj = super().get_object()
        obj.blog_view += 1
        obj.save()
        return obj
Ulvi
  • 965
  • 12
  • 31
Adi Nishad
  • 23
  • 1
  • 6
  • 3
    While this code may provide a solution to problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution. – palaѕн May 12 '20 at 07:25
  • using this view increase by 2 each time request encounter – itsvinayak Oct 03 '20 at 05:48