Overlord
Overlord

Reputation: 152

Store client IP on model on requests in Django restframework

I would like to store my client's Ip in my model in django restframework. I don't know where to put my function and how to store it when a log gets created:

Models.py

class Loglist(models.Model):
"""This class represents the loglist model."""
message = JSONField(null=True)
date_created = models.TimeField(auto_now_add=True)
client_ip = models.GenericIPAddressField(null=True)

def __str__(self):
    """Return a human readable representation of the model instance."""
    return "{}".format(self.client_ip)

Views.py

class CreateView(generics.ListCreateAPIView):
    """This class defined the create behaviour of our rest api."""
    queryset = Loglist.objects.all()
    serializer_class = LoglistSerializer

    def perform_create(self, serializer):
        serializer.save()

class DetailsView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Loglist.objects.all()
    serializer_class = LoglistSerializer

Serializer.py

class LoglistSerializer(serializers.ModelSerializer):
    """Serializer to map the model instance into JSON format."""

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = Loglist
        fields = ('id', 'message', 'date_created', 'client_ip')
        read_only_fields = ('date_created', 'client_ip')

Upvotes: 1

Views: 3677

Answers (1)

Ahsan Malik
Ahsan Malik

Reputation: 152

The ip address of request.user can be found in request.META.get('REMOTE_ADDR') And you can override the create function of the serializer to store the ip address of the user that is creating the Loglist.

class LoglistSerializer(serializers.ModelSerializer):
    """Serializer to map the model instance into JSON format."""

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = Loglist
        fields = ('id', 'message', 'date_created', 'client_ip')
        read_only_fields = ('date_created', 'client_ip')
    
    def create(self, validated_data):
        validated_data['client_ip'] = self.context.get('request').META.get("REMOTE_ADDR")
        return Loglist.objects.create(**validated_data)

Upvotes: 4

Related Questions