Menu Close

How to get user IP address in Python Django?

To get user IP address in Python Django, we get the HTTP_X_FORWARDED_FOR request header.

For instance, we write

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]
        ip = request.META.get('REMOTE_ADDR')
    return ip

to create the get_client_ip function that takes the view’s request object.

And we get the user IP address with


If that’s not available, we use


to get the user’s IP address.

Posted in Python, Python Answers