Retrieve User IP Address in Django

I’ve often needed to capture the IP addresses of users visiting my Django applications. Whether for logging, analytics, or security purposes, knowing how to reliably get the user IP address is crucial. Although it sounds easy, there are nuances to consider, especially when your app is behind proxies or load balancers.

In this guide, I’ll walk you through practical methods to retrieve the user IP address in Django. I’ll share working code examples and explain when and why to use each approach. By the end, you’ll be equipped to implement IP address capture confidently in your projects.

Methods to Get the User IP Address

In many web applications, the user’s IP address plays a key role. For example:

  • Tracking visitor locations for analytics or personalized content
  • Implementing IP-based access controls or rate limiting
  • Logging for security audits and detecting suspicious activity

However, due to the nature of HTTP requests and network setups, capturing the correct IP isn’t always straightforward. Proxies, VPNs, or cloud infrastructure can mask the original IP, so it’s important to understand how to handle these cases.

Check out Django User Registration with Email Confirmation

Method 1: Use request.META to Get the IP Address

The simplest way to get the IP address in Django is by accessing the request.META dictionary, which contains HTTP headers and metadata about the request.

Here’s an easy example:

from django.http import HttpResponse

def get_client_ip(request):
    ip = request.META.get('REMOTE_ADDR')
    return HttpResponse(f"Your IP address is {ip}")

You can refer to the screenshot below to see the output.

django get ip address

In this snippet, REMOTE_ADDR holds the IP address of the client making the request. However, this works reliably only if your Django app is directly exposed to the internet.

Read Python Django Import Functions

Method 2: Handle Proxies with HTTP_X_FORWARDED_FOR

In many production environments, Django apps run behind proxies or load balancers (like Nginx, AWS ELB, or Cloudflare). In this case, REMOTE_ADDR might return the proxy’s IP instead of the actual user IP.

To handle this, you can check the HTTP_X_FORWARDED_FOR header, which proxies use to pass the original client IP.

Here’s a more robust function:

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        # X-Forwarded-For can contain multiple IPs, client IP is the first one
        ip = x_forwarded_for.split(',')[0].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

You can refer to the screenshot below to see the output.

django ip

You can refer to the screenshot below to see the output.

This method ensures you get the real client IP when behind proxies, but it depends on your proxy configuration forwarding this header correctly.

Check out Python Django Convert Date Time to String

Method 3: Use Middleware for Centralized IP Extraction

If you need to access the user IP frequently across your views, it’s efficient to create middleware that attaches the IP to the request object.

Here’s a simple middleware example:

class GetClientIPMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0].strip()
        else:
            ip = request.META.get('REMOTE_ADDR')
        request.client_ip = ip
        response = self.get_response(request)
        return response

To use this middleware:

  1. Save it in a file, e.g., middleware.py inside your Django app.
  2. Add it to your MIDDLEWARE list in settings.py:
MIDDLEWARE = [
    # ... existing middleware ...
    'yourapp.middleware.GetClientIPMiddleware',
]

Now, in any view, you can access request.client_ip directly:

from django.http import HttpResponse

def home(request):
    ip = getattr(request, 'client_ip', 'Unknown')
    return HttpResponse(f"Your IP address is {ip}")

You can refer to the screenshot below to see the output.

django get client ip

Important Considerations

  • Trusting HTTP_X_FORWARDED_FOR: Since this header can be spoofed by a malicious client, only trust it if your app is behind a trusted proxy that sets it correctly.
  • Multiple IPs in X-Forwarded-For: Sometimes this header contains a list of IPs. The first IP is usually the client’s real IP, but verify based on your infrastructure.
  • IPv6 vs IPv4: IP addresses can be in either format. Your code should handle both transparently (which it does by default).
  • Security: Avoid using IP addresses alone for critical security decisions since they can be shared or masked.

Read Register User with OTP Verification in Django

Full Working Example: Django View to Show User IP

Here’s a complete Django view example that uses the robust method to get the user’s IP:

from django.http import HttpResponse

def get_user_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return HttpResponse(f"Your IP address is: {ip}")

Add this view to your urls.py:

from django.urls import path
from .views import get_user_ip

urlpatterns = [
    path('ip/', get_user_ip, name='get_user_ip'),
]

Now, when you visit /ip/ on your Django site, it will display your IP address.

By following these methods, you can reliably capture user IP addresses in your Django applications. Whether you’re building analytics tools, security features, or personalized content, this knowledge is fundamental.

If you’re deploying behind proxies, always verify your infrastructure’s forwarding headers to ensure accuracy. Implementing middleware can save you time and keep your code clean.

I hope you found this guide helpful. If you have any questions or want to share your experiences, feel free to leave a comment below.

For a deeper dive into Django request handling and middleware, keep exploring and experimenting, that’s how we grow as developers!

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.