djangopython-3.xubuntu-16.04geoip2

Django geoip2 + Maxmind working locally, but not in production?


I'm able to get a response object and render it to the page locally, but on my live site it doesn't work.

I'm using Maxmind's binary database, which is the GeoLite2-City.mmdb file in my project folder.

This also works in my website's Ubuntu 16.04 terminal:

import geoip2.database
reader = geoip2.database.Reader('/home/jake/project-main/project/GeoLite2-City.mmdb')
ip = request.META.get('REMOTE_ADDR', None)
location_lookup_response = reader.city(ip)
print(location_lookup_resonse)

However, it doesn't work on the site. Any thoughts here are appreciated.


Solution

  • In your settings.py file, you should have the GEOIP_PATH set to the directory which contains the GeoLite2-*.mmdb files. The documentation for that can be found here.

    Once the *.mmdb files are in the GEOIP_PATH, you should be able to find them using the django shell:

    $ python manage.py shell
    
    >>> from django.conf import settings
    >>> print(settings.GEOIP_PATH)
    '/path/to/geoip-mmdb-files'
    
    >>> import os
    >>> os.listdir(settings.GEOIP_PATH)
    ['GeoLite2-City.mmdb', 'GeoLite2-Country.mmdb']
    
    >>> from django.contrib.gis.geoip2 import GeoIP2
    >>> g = GeoIP2()
    >>> g.country('google.com')
    {'country_code': 'US', 'country_name': 'United States'}