Save the ip when sending a form django


I want to add a field in the Post class that stores the ip of the person who sends the form. This is my "" file

from django.db import models
from django.utils import timezone

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date =

    def __str__(self):
        return self.title

I have tried to put genericipaddress_field = models.GenericIPAddressField(blank=True, null=True) in the Post model, but evidently it has not worked and you have saved it blank

asked by ImHarvol 23.07.2017 в 19:16

1 answer


It is not enough to have the field in the model:

genericipaddress_field = models.GenericIPAddressField(blank=True, null=True)

You also need in the view saved by the Post to obtain the ip of the request and save it. For example, I use this function in the views I need:

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]
        ip = request.META.get('REMOTE_ADDR')
    return ip

This function I call in the view that receives the request with the new post.

answered by 23.07.2017 / 21:34