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]
else:
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
request.META.get('HTTP_X_FORWARDED_FOR')
If that’s not available, we use
request.META.get('REMOTE_ADDR')
to get the user’s IP address.