new seriliazer fields and views for blog with ip
This commit is contained in:
@@ -4,10 +4,10 @@ from .models import BlogModel
|
||||
class BlogSerilizer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = BlogModel
|
||||
fields = "__all__"
|
||||
fields = ['title','author', 'slug', 'category', 'created_at', 'updated_at', 'cover_image', 'views']
|
||||
|
||||
|
||||
class AllBlogSerilizer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = BlogModel
|
||||
fields = "__all__"
|
||||
exclude = ('is_published',)
|
||||
+25
-1
@@ -45,10 +45,34 @@ class AllBlogView(APIView):
|
||||
class BlogView(APIView):
|
||||
authentication_classes = []
|
||||
serializer_class = BlogSerilizer
|
||||
|
||||
def get_client_ip(self, request):
|
||||
"""Helper function to get the client IP from request headers."""
|
||||
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
|
||||
|
||||
|
||||
def get(self, request, pk):
|
||||
blog = get_object_or_404(BlogModel, pk=pk)
|
||||
if blog.is_published:
|
||||
# Track views using session
|
||||
client_ip = self.get_client_ip(request)
|
||||
session_key = f'viewed_blog_{pk}_{client_ip}'
|
||||
|
||||
if not request.session.get(session_key):
|
||||
blog.views += 1
|
||||
blog.save()
|
||||
print(f'views {blog.views}')
|
||||
print(session_key)
|
||||
request.session[session_key] = True
|
||||
request.session.set_expiry(3600)
|
||||
|
||||
blog_ser = self.serializer_class(instance=blog, context={'request': request})
|
||||
return Response(blog_ser.data, status=status.HTTP_200_OK)
|
||||
else:
|
||||
return Response({'detail': 'object with the given id does not exiest or its not published yet'}, status=status.HTTP_404_NOT_FOUND)
|
||||
return Response({'detail': 'object with the given id does not exist or is not published yet'},
|
||||
status=status.HTTP_404_NOT_FOUND)
|
||||
Reference in New Issue
Block a user