How to Get User IP Address in Django ?

Published On: 19/07/2022 | Category: Django Python

Hi Dev,

If you need to see example of how do i get user ip address in django. let’s discuss about how to get visitor ip address for a django. This article will give you simple example of how to get a client ip address in django using python. I’m going to show you about how to get user ip address in python. So, let's follow few step to create example of how to get user ip address in django.

We will use in this example HttpResponse render the view returns an httpresponse object that contains the generated response.

Let's see bellow example here you will learn get user ip address in django.

Example: views.py
from django.shortcuts import render
from django.http import HttpResponse

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 HttpResponse(ip)
Output
127.0.0.1

I Hope It will help you....