pythondjangogeolocationdjango-contrib

Creating project settings for GeoIP2 in Django


I'm trying to play around with GeoIP2 for Django, which require you to set the path to your country and city datasets in a GEOIP_PATH setting. My issue is that I don't know where I'm supposed to put this setting so that something like the Python shell can see it.

I assume it would go in settings.py, but I'm unsure as to the syntax for this particular module, and the Django documentation is absolute rubbish regarding this.


Solution

  • You're correct that it should be placed inside the settings.py file in Django. You should be able to find this file somewhere in your Django project/app. You then place the following in that file:

    GEOIP_PATH = '/path/to/your/geoip/datafiles'
    

    GEOIP willl then be able to locate the files it requires for usage in the application.

    Edit


    If you want to try GeoIP2 for Django via a python shell you will have to follow the following steps (please note I'm using Windows for this answer, but it should be the same for linux based operating systems):

    Note: If you already have a Django project set up you can start at step 10.

    1. Make sure you have Python installed (I'm using Python 3.5.1 for this answer), inlucding pip.

    2. Install virtualenvwrapper: pip install virtualenvwrapper-win (or pip install virtualenvwrapper for non-windows install)

    3. Make a virtual environment for your project: mkvirtualenv GeoIP

    4. Install Django for this project: pip install django

    5. To check the installation succeeded execute django-admin --version, this should show you the version of the Django installtion, which is 1.9.1 for me. If you do not see this, make sure your python installation is correct.

    6. Create a directory where you want your projects to be saved. In my case I made a directory called Django: mkdir Django

    7. Move to this directory: cd Django

    8. Create a Django project: django-admin startproject geoip_test

    9. Move to the new directory Django created for you: cd geoip_test

    10. Install geoip2: pip install geoip2

    11. Create a directory to store the required datasets. Please note that these have to be unzipped: mkdir geoip. Place the files you downloaded and unzipped in this directory.

    12. Start a Django Python shell: python manage.py shell

    13. Import GeoIP2: >>> from django.contrib.gis.geoip2 import GeoIP2

    14. Create a GeoIP2 object by instantiating a class with a path to the location of the files you downloaded: >>> g = GeoIP2('geoip')

    15. Test that everything works: >>> g.country('google.com')
      {'country_code': 'US', 'country_name': 'United States'}