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 import RequestContext
from django.shortcuts import render_to_response
def home(request):
g = GeoIP()
client_ip = request.META['REMOTE_ADDR']
lat,long = g.lat_lon(client_ip)
return render_to_response('home_page_tmp.html',locals())
But I get this error:
KeyError at /mypage/
'REMOTE_ADDR'
Request Method: GET
Request URL: http://mywebsite.com/mypage/
Django Version: 1.2.4
Exception Type: KeyError
Exception Value:
'REMOTE_ADDR'
Exception Location: /mysite/homepage/views.py in home, line 9
Python Executable: /usr/bin/python
Python Version: 2.6.6
Python Path: ['/mysite', '/usr/local/lib/python2.6/dist-packages/flup-1.0.2-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/pymodules/python2.6']
Server time: Sun, 2 Jan 2011 20:42:50 -0600
I would like to suggest an improvement to yanchenko's answer.
Instead of taking the first ip in the X_FORWARDED_FOR list, I take the first one which in not a known internal ip, as some routers don't respect the protocol, and you can see internal ips as the first value of the list.
I hope this helps fellow Googlers who have the same problem.
You can use django-ipware which supports Python 2 & 3 and handles IPv4 & IPv6.
Install:
Simple Usage:
Advanced Usage:
Note: read this notice.
The simpliest solution (in case you are using fastcgi+nignx) is what itgorilla commented:
Ps: I added this answer just to make his solution more visible.
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;