How to Know a Users Ip Address Using Django

how to know a users ip address using django

Introduction

pip3 install Django

Project setup

To begin let’s first create our project by running the command below.

django-admin startproject django_my_ip

After the above command executes successfully, cd into the directory and run the command below to create our app

python3 manage.py startapp my_ip

Project Configuration

Now we need to register the application to our project, to do so, in the settings.py file add the following code in the installed apps as shown below.


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'my_ip',
]

Create project view

Inside the my_ip folder add the following code in the views.py file.

from django.shortcuts import render
from django.http import HttpResponse


def show_ip(request):
    ip_address = request.META.get('REMOTE_ADDR')
    return render(request, 'my_ip/index.html', {'ip_address': ip_address})

Create templates

Now let’s create a template to interact with our application. Inside the my_ip folder create a folder called templates and inside it create a folder called my_ip and create a file called index.html.

Inside the index.html file insert the following.

<!DOCTYPE html>
<html>
<head>
    <title>Hello, World!</title>
</head>
<body>
    <style>
        div{
            text-align: center;
        }
    </style>
    <div>
        <h1>Hello, World!</h1><br>
        <p>Your IP address is: {{ ip_address }}</p>
    </div>
    
</body>
</html>

Create app routes

Inside the my_ip create a file called urls.py and add the code below.

from django.urls import path 
from . import views


urlpatterns = [
    path('',views.show_ip, name="index"),
]

Create project routes

Now let’s map our app to our project, to do so, add the following code in the urls.py inside the django_my_ip folder.

from django.contrib import admin
from django.urls import path,include 

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('my_ip.urls')),
]

Run

Now open your terminal and run the command below to start the server.

python3 manage.py runserver

Results

After you run the command above your application should be available at the address [ http://127.0.0.1:8000 ] as shown below.

There you have it, Thanks for reading. Happy Coding.

Leave a Comment

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