Building a location aware web app with GeoDjango
Published by Matthew Daly at 26th March 2016 9:30 pm
PostgreSQL has excellent support for geographical data thanks to the PostGIS extension, and Django allows you to take full advantage of it thanks to GeoDjango. In this tutorial, I'll show you how to use GeoDjango to build a web app that allows users to search for gigs and events near them.
Requirements
I've made the jump to Python 3, and if you haven't done so yet, I highly recommend it - it's not hard, and there's very few modules left that haven't been ported across. As such, this tutorial assumes you're using Python 3. You'll also need to have Git, PostgreSQL and PostGIS installed - I'll leave the details of doing so up to you as it varies by platform, but you can generally do so easily with a package manager on most Linux distros. On Mac OS X I recommend using Homebrew. If you're on Windows I think your best bet is probably to use a Vagrant VM.
We'll be using Django 1.9 - if by the time you read this a newer version of Django is out, it's quite possible that some things may have changed and you'll need to work around any problems caused. Generally search engines are the best place to look for this, and I'll endeavour to keep the resulting Github repository as up to date as I can, so try those if you get stuck.
Getting started
First of all, let's create our database. Make sure you're running as a user that has the required privileges to create users and databases for PostgreSQL and run the following command:
$ createdb gigfinder
This creates the database. Next, we create the user:
$ createuser -s giguser -P
You'll be prompted to enter a password for the new user. Next, we want to use the psql
command-line client to interact with our new database:
$ psql gigfinder
This connects to the database. Run these commands to set up access to the database and install the PostGIS extension:
1# GRANT ALL PRIVILEGES ON DATABASE gigfinder TO giguser;2# CREATE EXTENSION postgis;3# \q
With our database set up, it's time to start work on our project. Let's create our virtualenv in a new folder:
$ pyvenv venv
Then activate it:
$ source venv/bin/activate
Then we install Django, along with a few other production dependencies:
$ pip install django-toolbelt
And record our dependencies:
$ pip freeze > requirements.txt
Next, we create our application skeleton:
$ django-admin.py startproject gigfinder .
We'll also create a .gitignore
file:
1venv/2.DS_Store3*.swp4node_modules/5*.pyc
Let's commit our changes:
1$ git init2$ git add .gitignore requirements.txt manage.py gigfinder3$ git commit -m 'Initial commit'
Next, let's create our first app, which we will call gigs
:
$ python manage.py startapp gigs
We need to add our new app to the INSTALLED_APPS
setting. While we're there we'll also add GIS support and set up the database connection. First, add the required apps to INSTALLED_APPS
:
1INSTALLED_APPS = [2 ...3 'django.contrib.gis',4 'gigs',5]
Next, configure the database:
1DATABASES = {2 'default': {3 'ENGINE': 'django.contrib.gis.db.backends.postgis',4 'NAME': 'gigfinder',5 'USER': 'giguser',6 'PASSWORD': 'password',7 },8}
Let's run the migrations:
1$ python manage.py migrate2Operations to perform:3 Apply all migrations: sessions, contenttypes, admin, auth4Running migrations:5 Rendering model states... DONE6 Applying contenttypes.0001_initial... OK7 Applying auth.0001_initial... OK8 Applying admin.0001_initial... OK9 Applying admin.0002_logentry_remove_auto_add... OK10 Applying contenttypes.0002_remove_content_type_name... OK11 Applying auth.0002_alter_permission_name_max_length... OK12 Applying auth.0003_alter_user_email_max_length... OK13 Applying auth.0004_alter_user_username_opts... OK14 Applying auth.0005_alter_user_last_login_null... OK15 Applying auth.0006_require_contenttypes_0002... OK16 Applying auth.0007_alter_validators_add_error_messages... OK17 Applying sessions.0001_initial... OK
And create our superuser account:
$ python manage.py createsuperuser
Now, we'll commit our changes:
1$ git add gigfinder/ gigs/2$ git commit -m 'Created gigs app'3[master e72a846] Created gigs app4 8 files changed, 24 insertions(+), 3 deletions(-)5 create mode 100644 gigs/__init__.py6 create mode 100644 gigs/admin.py7 create mode 100644 gigs/apps.py8 create mode 100644 gigs/migrations/__init__.py9 create mode 100644 gigs/models.py10 create mode 100644 gigs/tests.py11 create mode 100644 gigs/views.py
Our first model
At this point, it's worth thinking about the models we plan for our app to have. First we'll have a Venue
model that contains details of an individual venue, which will include a name and a geographical location. We'll also have an Event
model that will represent an individual gig or event at a venue, and will include a name, date/time and a venue as a foreign key.
Before we start writing our first model, we need to write a test for it, but we also need to be able to create objects easily in our tests. We also want to be able to easily examine our objects, so we'll install iPDB and Factory Boy:
1$ pip install ipdb factory-boy2$ pip freeze > requirements.txt
Next, we write a test for the Venue
model:
1from django.test import TestCase2from gigs.models import Venue3from factory.fuzzy import BaseFuzzyAttribute4from django.contrib.gis.geos import Point5import factory.django, random67class FuzzyPoint(BaseFuzzyAttribute):8 def fuzz(self):9 return Point(random.uniform(-180.0, 180.0),10 random.uniform(-90.0, 90.0))1112# Factories for tests13class VenueFactory(factory.django.DjangoModelFactory):14 class Meta:15 model = Venue16 django_get_or_create = (17 'name',18 'location'19 )2021 name = 'Wembley Arena'22 location = FuzzyPoint()2324class VenueTest(TestCase):25 def test_create_venue(self):26 # Create the venue27 venue = VenueFactory()2829 # Check we can find it30 all_venues = Venue.objects.all()31 self.assertEqual(len(all_venues), 1)32 only_venue = all_venues[0]33 self.assertEqual(only_venue, venue)3435 # Check attributes36 self.assertEqual(only_venue.name, 'Wembley Arena')
Note that we randomly generate our location - this is done as suggested in this Stack Overflow post.
Now, running our tests brings up an expected error:
1$ python manage.py test gigs2Creating test database for alias 'default'...3E4======================================================================5ERROR: gigs.tests (unittest.loader._FailedTest)6----------------------------------------------------------------------7ImportError: Failed to import test module: gigs.tests8Traceback (most recent call last):9 File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 428, in _find_test_path10 module = self._get_module_from_name(name)11 File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name12 __import__(name)13 File "/Users/matthewdaly/Projects/gigfinder/gigs/tests.py", line 2, in <module>14 from gigs.models import Venue15ImportError: cannot import name 'Venue'161718----------------------------------------------------------------------19Ran 1 test in 0.001s2021FAILED (errors=1)22Destroying test database for alias 'default'...
Let's create our Venue
model in gigs/models.py
:
1from django.contrib.gis.db import models23class Venue(models.Model):4 """5 Model for a venue6 """7 pass
For now, we're just creating a simple dummy model. Note that we import models
from django.contrib.gis.db
instead of the usual place - this gives us access to the additional geographical fields.
If we run our tests again we get an error:
1$ python manage.py test gigs2Creating test database for alias 'default'...3Traceback (most recent call last):4 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute5 return self.cursor.execute(sql, params)6psycopg2.ProgrammingError: relation "gigs_venue" does not exist7LINE 1: SELECT "gigs_venue"."id" FROM "gigs_venue" ORDER BY "gigs_ve...8 ^91011The above exception was the direct cause of the following exception:1213Traceback (most recent call last):14 File "manage.py", line 10, in <module>15 execute_from_command_line(sys.argv)16 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line17 utility.execute()18 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute19 self.fetch_command(subcommand).run_from_argv(self.argv)20 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv21 super(Command, self).run_from_argv(argv)22 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv23 self.execute(*args, **cmd_options)24 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/commands/test.py", line 74, in execute25 super(Command, self).execute(*args, **options)26 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute27 output = self.handle(*args, **options)28 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/commands/test.py", line 90, in handle29 failures = test_runner.run_tests(test_labels)30 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/test/runner.py", line 532, in run_tests31 old_config = self.setup_databases()32 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/test/runner.py", line 482, in setup_databases33 self.parallel, **kwargs34 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/test/runner.py", line 726, in setup_databases35 serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),36 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 78, in create_test_db37 self.connection._test_serialized_contents = self.serialize_db_to_string()38 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 122, in serialize_db_to_string39 serializers.serialize("json", get_objects(), indent=None, stream=out)40 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/serializers/__init__.py", line 129, in serialize41 s.serialize(queryset, **options)42 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/serializers/base.py", line 79, in serialize43 for count, obj in enumerate(queryset, start=1):44 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 118, in get_objects45 for obj in queryset.iterator():46 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/models/query.py", line 52, in __iter__47 results = compiler.execute_sql()48 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql49 cursor.execute(sql, params)50 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute51 return self.cursor.execute(sql, params)52 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/utils.py", line 95, in __exit__53 six.reraise(dj_exc_type, dj_exc_value, traceback)54 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise55 raise value.with_traceback(tb)56 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute57 return self.cursor.execute(sql, params)58django.db.utils.ProgrammingError: relation "gigs_venue" does not exist59LINE 1: SELECT "gigs_venue"."id" FROM "gigs_venue" ORDER BY "gigs_ve...
Let's update our model:
1from django.contrib.gis.db import models23class Venue(models.Model):4 """5 Model for a venue6 """7 name = models.CharField(max_length=200)8 location = models.PointField()
Then create our migration:
1$ python manage.py makemigrations2Migrations for 'gigs':3 0001_initial.py:4 - Create model Venue
And run it:
1$ python manage.py migrate2Operations to perform:3 Apply all migrations: gigs, sessions, contenttypes, auth, admin4Running migrations:5 Rendering model states... DONE6 Applying gigs.0001_initial... OK
Then if we run our tests:
1$ python manage.py test gigs2Creating test database for alias 'default'...3.4----------------------------------------------------------------------5Ran 1 test in 0.362s67OK8Destroying test database for alias 'default'...
They should pass. Note that Django may complain about needing to delete the test database before running the tests, but this should not cause any problems. Let's commit our changes:
1$ git add requirements.txt gigs/2$ git commit -m 'Venue model in place'
With our venue done, let's turn to our Event
model. Amend gigs/tests.py
as follows:
1from django.test import TestCase2from gigs.models import Venue, Event3from factory.fuzzy import BaseFuzzyAttribute4from django.contrib.gis.geos import Point5import factory.django, random6from django.utils import timezone78class FuzzyPoint(BaseFuzzyAttribute):9 def fuzz(self):10 return Point(random.uniform(-180.0, 180.0),11 random.uniform(-90.0, 90.0))1213# Factories for tests14class VenueFactory(factory.django.DjangoModelFactory):15 class Meta:16 model = Venue17 django_get_or_create = (18 'name',19 'location'20 )2122 name = 'Wembley Arena'23 location = FuzzyPoint()2425class EventFactory(factory.django.DjangoModelFactory):26 class Meta:27 model = Event28 django_get_or_create = (29 'name',30 'venue',31 'datetime'32 )3334 name = 'Queens of the Stone Age'35 datetime = timezone.now()3637class VenueTest(TestCase):38 def test_create_venue(self):39 # Create the venue40 venue = VenueFactory()4142 # Check we can find it43 all_venues = Venue.objects.all()44 self.assertEqual(len(all_venues), 1)45 only_venue = all_venues[0]46 self.assertEqual(only_venue, venue)4748 # Check attributes49 self.assertEqual(only_venue.name, 'Wembley Arena')505152class EventTest(TestCase):53 def test_create_event(self):54 # Create the venue55 venue = VenueFactory()5657 # Create the event58 event = EventFactory(venue=venue)5960 # Check we can find it61 all_events = Event.objects.all()62 self.assertEqual(len(all_events), 1)63 only_event = all_events[0]64 self.assertEqual(only_event, event)6566 # Check attributes67 self.assertEqual(only_event.name, 'Queens of the Stone Age')68 self.assertEqual(only_event.venue.name, 'Wembley Arena')
Then we run our tests:
1$ python manage.py test gigs2Creating test database for alias 'default'...3E4======================================================================5ERROR: gigs.tests (unittest.loader._FailedTest)6----------------------------------------------------------------------7ImportError: Failed to import test module: gigs.tests8Traceback (most recent call last):9 File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 428, in _find_test_path10 module = self._get_module_from_name(name)11 File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name12 __import__(name)13 File "/Users/matthewdaly/Projects/gigfinder/gigs/tests.py", line 2, in <module>14 from gigs.models import Venue, Event15ImportError: cannot import name 'Event'161718----------------------------------------------------------------------19Ran 1 test in 0.001s2021FAILED (errors=1)22Destroying test database for alias 'default'...
As expected, this fails, so create an empty Event
model in gigs/models.py
:
1class Event(models.Model):2 """3 Model for an event4 """5 pass
Running the tests now will raise an error due to the table not existing:
1$ python manage.py test gigs2Creating test database for alias 'default'...3Traceback (most recent call last):4 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute5 return self.cursor.execute(sql, params)6psycopg2.ProgrammingError: relation "gigs_event" does not exist7LINE 1: SELECT "gigs_event"."id" FROM "gigs_event" ORDER BY "gigs_ev...8 ^91011The above exception was the direct cause of the following exception:1213Traceback (most recent call last):14 File "manage.py", line 10, in <module>15 execute_from_command_line(sys.argv)16 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line17 utility.execute()18 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute19 self.fetch_command(subcommand).run_from_argv(self.argv)20 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv21 super(Command, self).run_from_argv(argv)22 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv23 self.execute(*args, **cmd_options)24 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/commands/test.py", line 74, in execute25 super(Command, self).execute(*args, **options)26 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute27 output = self.handle(*args, **options)28 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/management/commands/test.py", line 90, in handle29 failures = test_runner.run_tests(test_labels)30 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/test/runner.py", line 532, in run_tests31 old_config = self.setup_databases()32 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/test/runner.py", line 482, in setup_databases33 self.parallel, **kwargs34 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/test/runner.py", line 726, in setup_databases35 serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),36 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 78, in create_test_db37 self.connection._test_serialized_contents = self.serialize_db_to_string()38 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 122, in serialize_db_to_string39 serializers.serialize("json", get_objects(), indent=None, stream=out)40 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/serializers/__init__.py", line 129, in serialize41 s.serialize(queryset, **options)42 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/serializers/base.py", line 79, in serialize43 for count, obj in enumerate(queryset, start=1):44 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 118, in get_objects45 for obj in queryset.iterator():46 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/models/query.py", line 52, in __iter__47 results = compiler.execute_sql()48 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql49 cursor.execute(sql, params)50 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute51 return self.cursor.execute(sql, params)52 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/utils.py", line 95, in __exit__53 six.reraise(dj_exc_type, dj_exc_value, traceback)54 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise55 raise value.with_traceback(tb)56 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute57 return self.cursor.execute(sql, params)58django.db.utils.ProgrammingError: relation "gigs_event" does not exist59LINE 1: SELECT "gigs_event"."id" FROM "gigs_event" ORDER BY "gigs_ev...
So let's populate our model:
1class Event(models.Model):2 """3 Model for an event4 """5 name = models.CharField(max_length=200)6 datetime = models.DateTimeField()7 venue = models.ForeignKey(Venue)
And create our migration:
1$ python manage.py makemigrations2Migrations for 'gigs':3 0002_event.py:4 - Create model Event
And run it:
1$ python manage.py migrate2Operations to perform:3 Apply all migrations: auth, admin, sessions, contenttypes, gigs4Running migrations:5 Rendering model states... DONE6 Applying gigs.0002_event... OK
And run our tests:
1$ python manage.py test gigs2Creating test database for alias 'default'...3..4----------------------------------------------------------------------5Ran 2 tests in 0.033s67OK8Destroying test database for alias 'default'...
Again, you may be prompted to delete the test database, but this should not be an issue.
With this done, let's commit our changes:
1$ git add gigs2$ git commit -m 'Added Event model'3[master 47ba686] Added Event model4 3 files changed, 67 insertions(+), 1 deletion(-)5 create mode 100644 gigs/migrations/0002_event.py
Setting up the admin
For an application like this, you'd expect the curators of the site to maintain the gigs and venues stored in the database, and that's an obvious use case for the Django admin. So let's set our models up to be available in the admin. Open up gigs/admin.py
and amend it as follows:
1from django.contrib import admin2from gigs.models import Venue, Event34admin.site.register(Venue)5admin.site.register(Event)
Now, if you start up the dev server as usual with python manage.py runserver
and visit http://127.0.0.1:8000/admin/, you can see that our Event
and Venue
models are now available. However, the string representations of them are pretty useless. Let's fix that. First, we amend our tests:
1from django.test import TestCase2from gigs.models import Venue, Event3from factory.fuzzy import BaseFuzzyAttribute4from django.contrib.gis.geos import Point5import factory.django, random6from django.utils import timezone78class FuzzyPoint(BaseFuzzyAttribute):9 def fuzz(self):10 return Point(random.uniform(-180.0, 180.0),11 random.uniform(-90.0, 90.0))1213# Factories for tests14class VenueFactory(factory.django.DjangoModelFactory):15 class Meta:16 model = Venue17 django_get_or_create = (18 'name',19 'location'20 )2122 name = 'Wembley Arena'23 location = FuzzyPoint()2425class EventFactory(factory.django.DjangoModelFactory):26 class Meta:27 model = Event28 django_get_or_create = (29 'name',30 'venue',31 'datetime'32 )3334 name = 'Queens of the Stone Age'35 datetime = timezone.now()3637class VenueTest(TestCase):38 def test_create_venue(self):39 # Create the venue40 venue = VenueFactory()4142 # Check we can find it43 all_venues = Venue.objects.all()44 self.assertEqual(len(all_venues), 1)45 only_venue = all_venues[0]46 self.assertEqual(only_venue, venue)4748 # Check attributes49 self.assertEqual(only_venue.name, 'Wembley Arena')5051 # Check string representation52 self.assertEqual(only_venue.__str__(), 'Wembley Arena')535455class EventTest(TestCase):56 def test_create_event(self):57 # Create the venue58 venue = VenueFactory()5960 # Create the event61 event = EventFactory(venue=venue)6263 # Check we can find it64 all_events = Event.objects.all()65 self.assertEqual(len(all_events), 1)66 only_event = all_events[0]67 self.assertEqual(only_event, event)6869 # Check attributes70 self.assertEqual(only_event.name, 'Queens of the Stone Age')71 self.assertEqual(only_event.venue.name, 'Wembley Arena')7273 # Check string representation74 self.assertEqual(only_event.__str__(), 'Queens of the Stone Age - Wembley Arena')
Next, we run our tests:
1$ python manage.py test gigs2Creating test database for alias 'default'...3FF4======================================================================5FAIL: test_create_event (gigs.tests.EventTest)6----------------------------------------------------------------------7Traceback (most recent call last):8 File "/Users/matthewdaly/Projects/gigfinder/gigs/tests.py", line 74, in test_create_event9 self.assertEqual(only_event.__str__(), 'Queens of the Stone Age - Wembley Arena')10AssertionError: 'Event object' != 'Queens of the Stone Age - Wembley Arena'11- Event object12+ Queens of the Stone Age - Wembley Arena131415======================================================================16FAIL: test_create_venue (gigs.tests.VenueTest)17----------------------------------------------------------------------18Traceback (most recent call last):19 File "/Users/matthewdaly/Projects/gigfinder/gigs/tests.py", line 52, in test_create_venue20 self.assertEqual(only_venue.__str__(), 'Wembley Arena')21AssertionError: 'Venue object' != 'Wembley Arena'22- Venue object23+ Wembley Arena242526----------------------------------------------------------------------27Ran 2 tests in 0.059s2829FAILED (failures=2)30Destroying test database for alias 'default'...
They fail as expected. So let's update gigs/models.py
:
1from django.contrib.gis.db import models23class Venue(models.Model):4 """5 Model for a venue6 """7 name = models.CharField(max_length=200)8 location = models.PointField()910 def __str__(self):11 return self.name121314class Event(models.Model):15 """16 Model for an event17 """18 name = models.CharField(max_length=200)19 datetime = models.DateTimeField()20 venue = models.ForeignKey(Venue)2122 def __str__(self):23 return "%s - %s" % (self.name, self.venue.name)
For the venue, we just use the name. For the event, we use the event name and the venue name.
Now, we run our tests again:
1$ python manage.py test gigs2Creating test database for alias 'default'...3..4----------------------------------------------------------------------5Ran 2 tests in 0.048s67OK8Destroying test database for alias 'default'...
Time to commit our changes:
1$ git add gigs2$ git commit -m 'Added models to admin'3[master 65d051f] Added models to admin4 3 files changed, 15 insertions(+), 1 deletion(-)
Our models are now in place, so you may want to log into the admin and create a few venues and events so you can see it in action. Note that the location field for the Venue
model creates a map widget that allows you to select a geographical location. It is a bit basic, however, so let's make it better. Let's install django-floppyforms
:
$ pip install django-floppyforms
And add it to our requirements:
$ pip freeze -r requirements.txt
Then add it to INSTALLED_APPS
in gigfinder/setttings.py
:
1INSTALLED_APPS = [2 ...3 'django.contrib.gis',4 'gigs',5 'floppyforms',6]
Now we create a custom point widget for our admin, a custom form for the venues, and a custom venue admin:
1from django.contrib import admin2from gigs.models import Venue, Event3from django.forms import ModelForm4from floppyforms.gis import PointWidget, BaseGMapWidget56class CustomPointWidget(PointWidget, BaseGMapWidget):7 class Media:8 js = ('/static/floppyforms/js/MapWidget.js',)910class VenueAdminForm(ModelForm):11 class Meta:12 model = Venue13 fields = ['name', 'location']14 widgets = {15 'location': CustomPointWidget()16 }1718class VenueAdmin(admin.ModelAdmin):19 form = VenueAdminForm2021admin.site.register(Venue, VenueAdmin)22admin.site.register(Event)
Note in particular that we define the media for our widget so we can include some required Javascript. If you run the dev server again, you should see that the map widget in the admin is now provided by Google Maps, making it much easier to identify the correct location of the venue.
Time to commit our changes:
1$ git add gigfinder/ gigs/ requirements.txt2$ git commit -m 'Customised location widget'
With our admin ready, it's time to move on to the user-facing part of the web app.
Creating our views
We will keep the front end for this app as simple as possible for the purposes of this tutorial, but of course you should feel free to expand upon this as you see fit. What we'll do is create a form that uses HTML5 geolocation to get the user's current geographical coordinates. It will then return events in the next week, ordered by how close the venue is. Please note that there are plans afoot in some browsers to prevent HTML5 geolocation from working unless content is server over HTTPS, so that may complicate things.
How do we query the database to get this data? It's not too difficult, as shown in this example:
1$ python manage.py shell2Python 3.5.1 (default, Mar 25 2016, 00:17:15)3Type "copyright", "credits" or "license" for more information.45IPython 4.1.2 -- An enhanced Interactive Python.6? -> Introduction and overview of IPython's features.7%quickref -> Quick reference.8help -> Python's own help system.9object? -> Details about 'object', use 'object??' for extra details.1011In [1]: from gigs.models import *1213In [2]: from django.contrib.gis.geos import Point1415In [3]: from django.contrib.gis.db.models.functions import Distance1617In [4]: location = Point(52.3749159, 1.1067473, srid=4326)1819In [5]: Venue.objects.all().annotate(distance=Distance('location', location)).order_by('distance')20Out[5]: [<Venue: Diss Corn Hall>, <Venue: Waterfront Norwich>, <Venue: UEA Norwich>, <Venue: Wembley Arena>]
I've set up a number of venues using the admin, one round the corner, two in Norwich, and one in London. I then imported the models, the Point
class, and the Distance
function, and created a Point
object. Note that the Point
is passed three fields - the first and second are the latitude and longitude, respectively, while the srid
field takes a value of 4326
. This field represents the Spatial Reference System Identifier used for this query - we've gone for WGS 84, which is a common choice and is referred to with the SRID 4326.
Now, we want the user to be able to submit the form and get the 5 nearest events in the next week. We can get the date for this time next week as follows:
In [6]: next_week = timezone.now() + timezone.timedelta(weeks=1)
Then we can get the events we want, sorted by distance, like this:
1In [7]: Event.objects.filter(datetime__gte=timezone.now()).filter(datetime__lte=next_week).annotate(distance=Distance('venue__location', location)).order_by('distance')[0:5]2Out[7]: [<Event: Primal Scream - UEA Norwich>, <Event: Queens of the Stone Age - Wembley Arena>]
With that in mind, let's write the test for our view. The view should contain a single form that accepts a user's geographical coordinates - for convenience we'll auto-complete this with HTML5 geolocation. On submit, the user should see a list of the five closest events in the next week.
First, let's test the GET request. Amend gigs/tests.py
as follows:
1from django.test import TestCase2from gigs.models import Venue, Event3from factory.fuzzy import BaseFuzzyAttribute4from django.contrib.gis.geos import Point5import factory.django, random6from django.utils import timezone7from django.test import RequestFactory8from django.core.urlresolvers import reverse9from gigs.views import LookupView1011class FuzzyPoint(BaseFuzzyAttribute):12 def fuzz(self):13 return Point(random.uniform(-180.0, 180.0),14 random.uniform(-90.0, 90.0))1516# Factories for tests17class VenueFactory(factory.django.DjangoModelFactory):18 class Meta:19 model = Venue20 django_get_or_create = (21 'name',22 'location'23 )2425 name = 'Wembley Arena'26 location = FuzzyPoint()2728class EventFactory(factory.django.DjangoModelFactory):29 class Meta:30 model = Event31 django_get_or_create = (32 'name',33 'venue',34 'datetime'35 )3637 name = 'Queens of the Stone Age'38 datetime = timezone.now()3940class VenueTest(TestCase):41 def test_create_venue(self):42 # Create the venue43 venue = VenueFactory()4445 # Check we can find it46 all_venues = Venue.objects.all()47 self.assertEqual(len(all_venues), 1)48 only_venue = all_venues[0]49 self.assertEqual(only_venue, venue)5051 # Check attributes52 self.assertEqual(only_venue.name, 'Wembley Arena')5354 # Check string representation55 self.assertEqual(only_venue.__str__(), 'Wembley Arena')565758class EventTest(TestCase):59 def test_create_event(self):60 # Create the venue61 venue = VenueFactory()6263 # Create the event64 event = EventFactory(venue=venue)6566 # Check we can find it67 all_events = Event.objects.all()68 self.assertEqual(len(all_events), 1)69 only_event = all_events[0]70 self.assertEqual(only_event, event)7172 # Check attributes73 self.assertEqual(only_event.name, 'Queens of the Stone Age')74 self.assertEqual(only_event.venue.name, 'Wembley Arena')7576 # Check string representation77 self.assertEqual(only_event.__str__(), 'Queens of the Stone Age - Wembley Arena')787980class LookupViewTest(TestCase):81 """82 Test lookup view83 """84 def setUp(self):85 self.factory = RequestFactory()8687 def test_get(self):88 request = self.factory.get(reverse('lookup'))89 response = LookupView.as_view()(request)90 self.assertEqual(response.status_code, 200)91 self.assertTemplateUsed('gigs/lookup.html')
Let's run our tests:
1$ python manage.py test gigs2Creating test database for alias 'default'...3E4======================================================================5ERROR: gigs.tests (unittest.loader._FailedTest)6----------------------------------------------------------------------7ImportError: Failed to import test module: gigs.tests8Traceback (most recent call last):9 File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 428, in _find_test_path10 module = self._get_module_from_name(name)11 File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name12 __import__(name)13 File "/Users/matthewdaly/Projects/gigfinder/gigs/tests.py", line 9, in <module>14 from gigs.views import LookupView15ImportError: cannot import name 'LookupView'161718----------------------------------------------------------------------19Ran 1 test in 0.000s2021FAILED (errors=1)22Destroying test database for alias 'default'...
Our first issue is that we can't import the view in the test. Let's fix that by amending gigs/views.py
:
1from django.shortcuts import render2from django.views.generic.base import View34class LookupView(View):5 pass
Running the tests again results in the following:
1$ python manage.py test gigs2Creating test database for alias 'default'...3.E.4======================================================================5ERROR: test_get (gigs.tests.LookupViewTest)6----------------------------------------------------------------------7Traceback (most recent call last):8 File "/Users/matthewdaly/Projects/gigfinder/gigs/tests.py", line 88, in test_get9 request = self.factory.get(reverse('lookup'))10 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/urlresolvers.py", line 600, in reverse11 return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))12 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/core/urlresolvers.py", line 508, in _reverse_with_prefix13 (lookup_view_s, args, kwargs, len(patterns), patterns))14django.core.urlresolvers.NoReverseMatch: Reverse for 'lookup' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []1516----------------------------------------------------------------------17Ran 3 tests in 0.154s1819FAILED (errors=1)20Destroying test database for alias 'default'...
We can't resolve the URL for our new view, so we need to add it to our URLconf. First of all, save this as gigs/urls.py
:
1from django.conf.urls import url2from gigs.views import LookupView34urlpatterns = [5 # Lookup6 url(r'', LookupView.as_view(), name='lookup'),7]
Then amend gigfinder/urls.py
as follows:
1from django.conf.urls import url, include2from django.contrib import admin34urlpatterns = [5 url(r'^admin/', admin.site.urls),67 # Gig URLs8 url(r'', include('gigs.urls')),9]
Then run the tests:
1$ python manage.py test gigs2Creating test database for alias 'default'...3.F.4======================================================================5FAIL: test_get (gigs.tests.LookupViewTest)6----------------------------------------------------------------------7Traceback (most recent call last):8 File "/Users/matthewdaly/Projects/gigfinder/gigs/tests.py", line 90, in test_get9 self.assertEqual(response.status_code, 200)10AssertionError: 405 != 2001112----------------------------------------------------------------------13Ran 3 tests in 0.417s1415FAILED (failures=1)16Destroying test database for alias 'default'...
We get a 405 response because the view does not accept GET requests. Let's resolve that:
1from django.shortcuts import render_to_response2from django.views.generic.base import View34class LookupView(View):5 def get(self, request):6 return render_to_response('gigs/lookup.html')
If we run our tests now:
1$ python manage.py test gigs2Creating test database for alias 'default'...3.E.4======================================================================5ERROR: test_get (gigs.tests.LookupViewTest)6----------------------------------------------------------------------7Traceback (most recent call last):8 File "/Users/matthewdaly/Projects/gigfinder/gigs/tests.py", line 89, in test_get9 response = LookupView.as_view()(request)10 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view11 return self.dispatch(request, *args, **kwargs)12 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch13 return handler(request, *args, **kwargs)14 File "/Users/matthewdaly/Projects/gigfinder/gigs/views.py", line 6, in get15 return render_to_response('gigs/lookup.html')16 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/shortcuts.py", line 39, in render_to_response17 content = loader.render_to_string(template_name, context, using=using)18 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/template/loader.py", line 96, in render_to_string19 template = get_template(template_name, using=using)20 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/template/loader.py", line 43, in get_template21 raise TemplateDoesNotExist(template_name, chain=chain)22django.template.exceptions.TemplateDoesNotExist: gigs/lookup.html2324----------------------------------------------------------------------25Ran 3 tests in 0.409s2627FAILED (errors=1)28Destroying test database for alias 'default'...
We see that the template is not defined. Save the following as gigs/templates/gigs/includes/base.html
:
1<!DOCTYPE html>2<html>3 <head>4 <title>Gig finder</title>5 <meta charset="utf-8">6 <meta http-equiv="X-UA-Compatible" content="IE=edge">7 <meta name="viewport" content="width=device-width, initial-scale=1">8 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></link>9 </head>10 <body>11 <h1>Gig Finder</h1>12 <div class="container">13 <div class="row">14 {% block content %}{% endblock %}15 </div>16 </div>17 <script src="https://code.jquery.com/jquery-2.2.2.min.js" integrity="sha256-36cp2Co+/62rEAAYHLmRCPIych47CvdM+uTBJwSzWjI=" crossorigin="anonymous"></script>18 <script language="javascript" type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>19 </body>20</html>
And the following as gigs/templates/gigs/lookup.html
:
1{% extends "gigs/includes/base.html" %}23{% block content %}4 <form role="form" action="/" method="post">{% csrf_token %}5 <div class="form-group">6 <label for="latitude">Latitude:</label>7 <input id="id_latitude" name="latitude" type="text" class="form-control"></input>8 </div>9 <div class="form-group">10 <label for="longitude">Longitude:</label>11 <input id="id_longitude" name="longitude" type="text" class="form-control"></input>12 </div>13 <input class="btn btn-primary" type="submit" value="Submit" />14 </form>15 <script language="javascript" type="text/javascript">16 navigator.geolocation.getCurrentPosition(function (position) {17 var lat = document.getElementById('id_latitude');18 var lon = document.getElementById('id_longitude');19 lat.value = position.coords.latitude;20 lon.value = position.coords.longitude;21 });22 </script>23{% endblock %}
Note the JavaScript to populate the latitude and longitude. Now, if we run our tests:
1$ python manage.py test gigs2Creating test database for alias 'default'...3...4----------------------------------------------------------------------5Ran 3 tests in 1.814s67OK8Destroying test database for alias 'default'...
Success! We now render our form as expected. Time to commit:
1$ git add gigs gigfinder2$ git commit -m 'Implemented GET handler'
Handling POST requests
Now we need to be able to handle POST requests and return the appropriate results. First, let's write a test for it in our existing LookupViewTest
class:
1 def test_post(self):2 # Create venues to return3 v1 = VenueFactory(name='Venue1')4 v2 = VenueFactory(name='Venue2')5 v3 = VenueFactory(name='Venue3')6 v4 = VenueFactory(name='Venue4')7 v5 = VenueFactory(name='Venue5')8 v6 = VenueFactory(name='Venue6')9 v7 = VenueFactory(name='Venue7')10 v8 = VenueFactory(name='Venue8')11 v9 = VenueFactory(name='Venue9')12 v10 = VenueFactory(name='Venue10')1314 # Create events to return15 e1 = EventFactory(name='Event1', venue=v1)16 e2 = EventFactory(name='Event2', venue=v2)17 e3 = EventFactory(name='Event3', venue=v3)18 e4 = EventFactory(name='Event4', venue=v4)19 e5 = EventFactory(name='Event5', venue=v5)20 e6 = EventFactory(name='Event6', venue=v6)21 e7 = EventFactory(name='Event7', venue=v7)22 e8 = EventFactory(name='Event8', venue=v8)23 e9 = EventFactory(name='Event9', venue=v9)24 e10 = EventFactory(name='Event10', venue=v10)2526 # Set parameters27 lat = 52.374915928 lon = 1.10674732930 # Put together request31 data = {32 'latitude': lat,33 'longitude': lon34 }35 request = self.factory.post(reverse('lookup'), data)36 response = LookupView.as_view()(request)37 self.assertEqual(response.status_code, 200)38 self.assertTemplateUsed('gigs/lookupresults.html')
If we now run this test:
1$ python manage.py test gigs2Creating test database for alias 'default'...3..F.4======================================================================5FAIL: test_post (gigs.tests.LookupViewTest)6----------------------------------------------------------------------7Traceback (most recent call last):8 File "/Users/matthewdaly/Projects/gigfinder/gigs/tests.py", line 117, in test_post9 self.assertEqual(response.status_code, 200)10AssertionError: 405 != 2001112----------------------------------------------------------------------13Ran 4 tests in 1.281s1415FAILED (failures=1)16Destroying test database for alias 'default'...
We can see that it fails because the POST method is not supported. Now we can start work on implementing it. First, let's create a form in gigs/forms.py
:
1from django.forms import Form, FloatField23class LookupForm(Form):4 latitude = FloatField()5 longitude = FloatField()
Next, edit gigs/views.py
:
1from django.shortcuts import render_to_response2from django.views.generic.edit import FormView3from gigs.forms import LookupForm4from gigs.models import Event5from django.utils import timezone6from django.contrib.gis.geos import Point7from django.contrib.gis.db.models.functions import Distance89class LookupView(FormView):10 form_class = LookupForm1112 def get(self, request):13 return render_to_response('gigs/lookup.html')1415 def form_valid(self, form):16 # Get data17 latitude = form.cleaned_data['latitude']18 longitude = form.cleaned_data['longitude']1920 # Get today's date21 now = timezone.now()2223 # Get next week's date24 next_week = now + timezone.timedelta(weeks=1)2526 # Get Point27 location = Point(longitude, latitude, srid=4326)2829 # Look up events30 events = Event.objects.filter(datetime__gte=now).filter(datetime__lte=next_week).annotate(distance=Distance('venue__location', location)).order_by('distance')[0:5]3132 # Render the template33 return render_to_response('gigs/lookupresults.html', {34 'events': events35 })
Note that we're switching from a View
to a FormView
so that it can more easily handle our form. We could render the form using this as well, but as it's a simple form I decided it wasn't worth the bother. Also, note that the longitude goes first - this caught me out as I expected the latitude to be the first argument.
Now, if we run our tests, they should complain about our missing template:
1$ python manage.py test gigs2Creating test database for alias 'default'...3..E.4======================================================================5ERROR: test_post (gigs.tests.LookupViewTest)6----------------------------------------------------------------------7Traceback (most recent call last):8 File "/Users/matthewdaly/Projects/gigfinder/gigs/tests.py", line 116, in test_post9 response = LookupView.as_view()(request)10 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view11 return self.dispatch(request, *args, **kwargs)12 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch13 return handler(request, *args, **kwargs)14 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/views/generic/edit.py", line 222, in post15 return self.form_valid(form)16 File "/Users/matthewdaly/Projects/gigfinder/gigs/views.py", line 31, in form_valid17 'events': events18 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/shortcuts.py", line 39, in render_to_response19 content = loader.render_to_string(template_name, context, using=using)20 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/template/loader.py", line 96, in render_to_string21 template = get_template(template_name, using=using)22 File "/Users/matthewdaly/Projects/gigfinder/venv/lib/python3.5/site-packages/django/template/loader.py", line 43, in get_template23 raise TemplateDoesNotExist(template_name, chain=chain)24django.template.exceptions.TemplateDoesNotExist: gigs/lookupresults.html2526----------------------------------------------------------------------27Ran 4 tests in 0.506s2829FAILED (errors=1)30Destroying test database for alias 'default'...
So let's create gigs/templates/gigs/lookupresults.html
:
1{% extends "gigs/includes/base.html" %}23{% block content %}4 <ul>5 {% for event in events %}6 <li>{{ event.name }} - {{ event.venue.name }}</li>7 {% endfor %}8 </ul>9{% endblock %}
Now, if we run our tests, they should pass:
1$ python manage.py test gigs2Creating test database for alias 'default'...3....4----------------------------------------------------------------------5Ran 4 tests in 0.728s67OK8Destroying test database for alias 'default'...
However, if we try actually submitting the form by hand, we get the error CSRF token missing or incorrect
. Edit views.py
as follows to resolve this:
1from django.shortcuts import render_to_response2from django.views.generic.edit import FormView3from gigs.forms import LookupForm4from gigs.models import Event5from django.utils import timezone6from django.contrib.gis.geos import Point7from django.contrib.gis.db.models.functions import Distance8from django.template import RequestContext910class LookupView(FormView):11 form_class = LookupForm1213 def get(self, request):14 return render_to_response('gigs/lookup.html', RequestContext(request))1516 def form_valid(self, form):17 # Get data18 latitude = form.cleaned_data['latitude']19 longitude = form.cleaned_data['longitude']2021 # Get today's date22 now = timezone.now()2324 # Get next week's date25 next_week = now + timezone.timedelta(weeks=1)2627 # Get Point28 location = Point(longitude, latitude, srid=4326)2930 # Look up events31 events = Event.objects.filter(datetime__gte=now).filter(datetime__lte=next_week).annotate(distance=Distance('venue__location', location)).order_by('distance')[0:5]3233 # Render the template34 return render_to_response('gigs/lookupresults.html', {35 'events': events36 })
Here we're adding the request context so that the CSRF token is available.
If you run the dev server, add a few events and venues via the admin, and submit a search, you'll see that you're returning events closest to you first.
Now that we can submit searches, we're ready to commit:
1$ git add gigs/2$ git commit -m 'Can now retrieve search results'
And we're done! Of course, you may want to expand on this by plotting each gig venue on a map, or something like that, in which case there's plenty of methods of doing so - you can retrieve the latitude and longitude in the template and use Google Maps to display them. I'll leave doing so as an exercise for the reader.
I can't say that working with GeoDjango isn't a bit of a struggle at times, but being able to make spatial queries in this fashion is very useful. With more and more people carrying smartphones, you're more likely than ever to be asked to build applications that return data based on someone's geographical location, and GeoDjango is a great way to do this with a Django application. You can find the source on Github.