DJANGO-CITY-LIGHT is an add-on provides models and commands to import country, region/state, and city data in your database.
the data is pulled from GeoNames and contains cities, regions/states, and countries.
This application is very simple and is useful if you want to make a simple address book for example. If you intend to build a fully featured spatial database, you should use django-cities.
- Python 2.7 or 3.3,
- Django >= 1.7
- MySQL or PostgreSQL or SQLite.
Open the terminal and Install Django-cities-light by running the following command:
pip install django-cities-light
Add cities_light to your INSTALLED_APPS as follows:
INSTALLED_APPS = ( 'django.contrib.humanize', 'cities_light', )
Configure filters to exclude data you don’t want, ie. you can filter out countries you don't want to pull data from as seen below:
CITIES_LIGHT_TRANSLATION_LANGUAGES = ['fr', 'en'] CITIES_LIGHT_INCLUDE_COUNTRIES = ['FR'] CITIES_LIGHT_INCLUDE_CITY_TYPES = ['PPL', 'PPLA', 'PPLA2', 'PPLA3', 'PPLA4', 'PPLC', 'PPLF', 'PPLG', 'PPLL', 'PPLR', 'PPLS', 'STLMT',]
Now, run migrations, it will only create tables for models that are not disabled:
python manage.py migrate
Loading/Updating data into the database.
Finally, populate your database with the following command:
python manage.py cities_light
Wait until the data is loaded into your database.
You can consult for help with the following command
python manage.py help cities_light
After installation and populating the database tables, you can use it within your models as follows
from cities_light.models import City class UserProfile(models.Model): city = models.ForeignKey(City) #taking for example the user profile model that requires city
To see what the
City object is like, open a shell session
python manage.py shell and type:
>>> from cities_light.models import City >>> cty = City.objects.get(id=100) # You can now access the cities by typing the following >>> cty.name 'Salon-de-Provence' >>> >>> cty.region <Region: Provence-Alpes-Côte d'Azur, France> >>> cty.country <Country: France> >>> cty.latitude Decimal('43.64229') >>> cty.longitude Decimal('5.09478') >>> cty.country.name 'France' >>>