I want to find the IP address of the user in django

Asked 2 years ago, Updated 2 years ago, 45 views

Find the user's IP address in django

When I run my code, I get an error, but I don't know where the problem is.

# 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())
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

django python

2022-09-21 21:26

1 Answers

It supports both IPv4 and IPv6, and I know it can be used on Python 2/3.

Install pip install django-ipware Code is

from ipware.ip import get_ip
ip = get_ip(request)
if ip is not None:
    print "I found it"
else:
    print "I couldn't find it"

You just need to change it slightly to that's all.

If this doesn't work, use the following method. It'll be harder to see than the code above.

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


2022-09-21 21:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.