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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With