Getting POST request IP address in Django

Server Side ProgrammingPythonProgramming

In this article, we will see how to get the IP address of from where we get POST request. It is sometimes important to keep a check on the security parameters. Sometimes you might need to ban some IPs or you might need to check if anyone is sending too many requests from a single IP. Let's see how it can be done easily with a third-party package.

Example

Create a Django project and an app. Setup urls and do some basic stuff like adding app in INSTALLED_APPS.

We will not use any Django forms or models.

First, install the django-ipware package −

pip install django-ipware

You don't need any configuration for this.

Now, go to Templates → home.html and add the following −

<!DOCTYPE html>
<html>
   <head>
      <title>tut</title>
   </head>
   <body>

      <form method="post" action= '/'
enctype="multipart/form-data">
               <input type="text" id= "text"/>
            <input type="submit" value="submit"/>
      </form>
   </body>
</html>

Here, we simply created a frontend for our form, which will be used to check the IP.

In app's urls.py

from django.urls import path, include
from . import views
urlpatterns = [
   path('',views.home,name='home'),
]

Here, we rendered our view.

In views.py

from django.shortcuts import render
from ipware import get_client_ip
def home(request):
   if request.method=="POST":
      # We get ip here
      client_ip, is_routable = get_client_ip(request)
      # Client IP is IP address
print(client_ip, is_routable)
   return render(request,'home.html')

Here, in POST request, we use get_client_ip() for seeing from which IP the request is coming, it returns two values.

Output

Keeping the fact in mind that we are using localhost, your output will be −

[23/Aug/2021 13:34:55] "GET / HTTP/1.1" 200 9999
127.0.0.1 False
[23/Aug/2021 13:34:58] "POST / HTTP/1.1" 200 9999
raja
Published on 25-Aug-2021 13:20:58
Advertisements