Last modified: Jan 10, 2023 By Alexander Williams
How to Get User Public Ip in Django
In this post, we'll show you how to get User Public Ip.
Getting User public ip
def get_user_public_ip(request):
""" Getting client Ip """
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
This function returns the user IP.
To understand, let's write an example.
Example
In this example, we'll write a function view that returns the IP of the client.
views.py
def get_client_ip(request):
""" Getting client Ip"""
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
def show_client_ip(request):
""" show ip adresse of client """
ip_adresse = get_client_ip(request)
return render(request, "adresse.html", {"ip_adresse":ip_adresse})
urls.py
#ip adresse
path('ip-adresse/', show_client_ip),
adresse.html
<!DOCTYPE html>
<html>
<head>
<title>Client ip adresse</title>
</head>
<body>
<h1>Your Ip Adresse: {{ip_adresse}}</h1>
</body>
</html>
Result:
As you can see, I got 127.0.0.1 IP because I'm on the localhost.