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