How do I get user\'s IP in django?
I have a view like this:
# Create your views
from django.contrib.gis.utils import GeoIP
from django.template impor
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
Make sure you have reverse proxy (if any) configured correctly (e.g. mod_rpaf
installed for Apache).
Note: the above uses the first item in X-Forwarded-For
, but you might want to use the last item (e.g., in the case of Heroku: Get client's real IP address on Heroku)
And then just pass the request as argument to it;
get_client_ip(request)