How to Get the User IP Address using Django

ip address in django

In this tutorial, we will learn how to get the user’s IP address using Django.

To understand this let’s learn about IP-Address.

Find IP Address in Django

The IP address is the address that distinguishes one network on the internet from another.

IP Address or Internet Protocol Address.

It is a unique identifier that is used to send and receive data from the internet on our devices.

We will make two functions that will help us to get the IP address of the user.

The first thing we have to do is start a project and start an app inside the project and follow the steps given below.

Steps to get the IP address of the user:

Step 1- Define two functions in which will store the IP address and show it as an output.

Step 2- Changes in to call the function.

Step 3- Output.

Step 1 –

In this, we have to define two functions.

The First will store the IP address and the second one will show the IP address.

To do so write the below code in your

from django.shortcuts import render

def get_ip_address(request):
    user_ip_address = request.META.get('HTTP_X_FORWARDED_FOR')
    if user_ip_address:
        ip = user_ip_address.split(',')[0]
        ip = request.META.get('REMOTE_ADDR')
    return ip

def show_ip_address(request):
    user_ip = get_ip_address(request)
    return render(request, "output.html", {"user_ip":user_ip})

The function get_ip_address will get the IP address of the user. X_FORWARDED_FORĀ variable will store the IP address of the user when the user is going through the load balancer.

Function show_ip_address will show the IP address of the user.

To call the functions we need to do some changes in

Step 2 –

We just now have created the functions in but we haven’t defined the path to navigate it. We need to do this in

To do so write the below code in

from django.contrib import admin
from django.urls import path
from ip_address.views import show_ip_address

urlpatterns = [

Now let’s see the output of the program.

Step 3 – Output:

Firstly we need to create an HTML file inside our project and name it output.html. This will show us the output in the browsing window in a proper manner.

Write the below code in the output.html file.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IP Address</title>
    <h1>Your IP Address: {{user_ip}}</h1>

Now run the program using the command python runserver and navigate to this will show the output.

The output of the program:

Your IP Address:

It is showing because I m on the localhost.

Thanks for reading this I hope you like this tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *