Geometry CRUD in Geodjango using Openlayers (Part 1)

Krishna G. Lodha
SpatialOps
Published in
5 min readOct 26, 2020

What is GeoDjango ? 🌏

Geodjango is an extension to the existing django framework where developer can leverage world class framework features available in django with the goodness of Geospatial Data 🌎 .Geodjango supports all databases such as PostgreSQL (PostGIS), MySQL , SQLite (SpatiaLite), Oracle, etc.

This enables us to use geometry data in the way it is intended, allowing user to do geospatial analysis (buffer, finding nearest points, etc.) .
Although best use case scenario for geodjango would be creating APIs and consuming from frontend frameworks like Angular , React, Vue.js , etc. that’s the topic for another post.

Prerequisite for this blog 📚

Before getting into actual CRUD operations with geodjango and openlayers, I accept you have little bit understanding of :
1. Django and Geodjango (Creating Models,Views, Templates, etc.)
2. PostgreSQL/ PostGIS (Creating and operating spatial database)
3. Openlayers 4 (Creating Map, Draw, Modify feature)
4. Excitement 😁 (Otherwise we are wasting time honey!)

How to get Started with GeoDjango ? 🐣

Geodjango has a fairly simple installation process on top of installing django, official documents can be fetched 👉🏻 here 👈🏻.
It’s a little bit trickier for Mac OS X though, but no worries! You can find the blog post for that 👉🏻 here 👈🏻

Image from https://giphy.com/

Step 1 : Setup Project 🚀

Once the geodjango is installed, follow these steps to setup project.
1. Create anaconda environment for django=3.1
2. Create Postgres database and install extension postGIS
3. Create a django-project and one app inside it
4. Make sure the settings.py file in django project has all settings as per the installation blog that you can find 👉🏻 here 👈🏻

By the end of these steps you should have something similar to 👉🏻 this 👈🏻

Once the project is ready open terminal and write

python manage.py makemigrations

to check if there are any changes in the database tables (We haven’t worked on it as of now)

python manage.py migrate

to make impression of models either added or edited via models.py file in db

Above two commands are only required when we make any changes in database tables definitions (adding/removing/updating column or it’s datatype, etc.)

python manage.py runserver

to start the django server and see the project working (default at http://localhost:8000/ )

which will popup this screen confirming everything is working fine. 😁

Screenshot of default django project working successfully

Step 2 : Setup Basic Map 🗺️

Now the project is running successfully, time to add map on the homepage.
A. Setup template for homepage

Django is a template based framework i.e. every HTML page needs to be added as a template in order to render on screen.
To create homepage template we’ll create a templates folder in mainapp, and then create home.html inside templates folder.

the basic home.html page setup will look like this:

mainapp/templates/home.html

B. Setup view to render template for homepage
Open ‘mainapp/views.py’
and add following view to the file

def Home(request):    return render(request,'home.html')

as we move forward we’ll add more things to the same function to load the location data on map, pass variables, etc.

creating view in ‘mainapp/views.py’

C. Setup url for homepage
This part will be little bit tricky, We can directly write url in the ‘crudgeodjangoproject/urls.py’ but doing this will get complicated in larger projects where we have multiple apps (e.g. app handling business logic, app handling authentications, etc.)
Thus we create a new urls.py file inside mainapp and then connect it with the central urls.py file using include method
Create a new urls.py file in mainapp folder and paste following code init

from django.urls import path
from . import views
urlpatterns = [
path('',views.Home, name='Home'),
]
mainapp/urls.py

Now we’ll connect urls.py of mainapp with urls.py of project, Head back to the urls.py of project and paste following code

from django.contrib import admin
from django.urls import path , include
urlpatterns =[
path('admin/',admin.site.urls),
path('', include('mainapp.urls')
]

by providing empty path (‘ ’) in the urlpatterns , we are basically telling django to load the mainapp.urls’ url directly with home route i.e. localhost:8000
If I add it like this

path('frommainapp/', include('mainapp.urls')

all the urls inside mainapp.urls will be used by adding ‘frommainapp’ in url i.e. localhost:8000/frommainapp

crudgeodjangoproject/urls.py

Once that is setup, again type the command

python manage.py runserver

— — — — — — — — — — - 🎊 The map is alive 🎉 — — — — — — — — — —

Before moving ahead we need to register a superuser so that we can access the functionalities of admin panel. Open terminal and put following command

python manage.py createsuperuser

put username , email (optional) , password to create superuser. Remeber this username for further use

Step 3 : Setup Geospatial Model 📄

Now that we have map setup, We can concentrate on creating a model (thus table in database) to store the geometry data (feel free to add more columns if you need).
I think it’s good time to take a break and have a recap of what we have done till now, make sure that you understand what we did and Why we did!
Take time to customise map , add some javascript libraries to make it beautiful ( bootstrap, materialize, etc. )

In the next post, we’ll work on model and get started with creating CRUD function . Make sure you subscribe to publication 👉🏻 here 👈🏻 and If you wanna follow the writer of this post tap 👉🏻 here 👈🏻.

About me

Hi, I’m Krishna Lodha, I’m a full stack Web GIS developer. I’m really enthusiastic about the power of locations and what story it tells us. Read more about me at http://krishnaglodha.com , to get more information about this code or suggest a better way to do it. ping me on LinkedIn at https://www.linkedin.com/in/krishnaglodha/

I write most of my post for the ‘Random GIS Talks’ , which is dedicated to posts regarding GIS installations, inventions, technologies, etc. make sure to hit the subscribe button to stay updated for further posts 👉🏻 here 👈🏻

Adios!

--

--