Python Answers

How to get user IP address in Python Django?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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