Search code examples
pythondjango

Error while setting up geoip for my site "GeoIP path must be a valid file or directory"


For my django app I am trying to store log of login location by amdin.

I created a middleware and trying use from "django.contrib.gis.utils import GeoIP" to get the latitude and longitude values of geo locations.

But getting error something like:

GeoIPException at /admin/

GeoIP path must be a valid file or directory.

code: trackware.py

from django.contrib.gis.utils import GeoIP
from core.models import Log # your simple Log model

def get_ip(request):
   xff = request.META.get('HTTP_X_FORWARDED_FOR')
   if xff:
      return xff.split(',')[0]
   return request.META.get('REMOTE_ADDR')

class UserLocationLoggerMiddleware(object):

    def process_request(self, request):
        if request.user and request.user.is_superuser:
            # Only log requests for superusers,
            # you can control this by adding a setting
            # to track other user types
            ip = get_ip(request)
            g = GeoIP()
            lat,long = g.lat_lon(ip)
            Log.objects.create(request.user, ip, lat, long)

changes that I made in settings.py:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',

#custom middleware
    'smartDNA.trackware.UserLocationLoggerMiddleware',
)

BASE_DIR = os.path.abspath(os.path.dirname(__file__))
GEOIP_PATH =os.path.join(BASE_DIR, 'geoip')

models.py:

class Log(models.Model):
    user = models.CharField(verbose_name="User",max_length=32)
    ip=models.IPAddressField(verbose_name="IP")
    lat= models.DecimalField(verbose_name="Lat",max_digits=10,decimal_places=1)
    long= models.DecimalField(verbose_name="Long",max_digits=10,decimal_places=1)

register model in admin.py:

admin.site.register(Log)

What is the mistake that I am doing and solution please....


Solution

  • From the documentation:

    In order to perform IP-based geolocation, the GeoIP object requires the GeoIP C libary and either the GeoIP Country or City datasets in binary format (the CSV files will not work!). These datasets may be downloaded from MaxMind. Grab the GeoLiteCountry/GeoIP.dat.gz and GeoLiteCity.dat.gz files and unzip them in a directory corresponding to what you set GEOIP_PATH with in your settings.

    Make sure you have done the above, otherwise the system does not know how to map IPs to locations.