Django with Mako template

Pawel Grajewski
2 min readMay 23, 2020

What is the next step when we want to create more robust application and sometimes we want some python manipulation in our template and not creating a special function in view. The first solution is to use a popular template framework called mako.

This solution allows creating python function in template and process context from Django views. Let’s start and create the Django project and next we will adjust it for mako templates. I will use pipenv for creating a project.

pipenv shell
pipenv install django
pipenv install mako
pipenv install djangomako

This will create virtual environment and install all necessary dependencies.

Next step is to create project and example app:

django-admin startproject makoProject .
python manage.py startapp makoApp

Now we can adjust our settings for using mako :

INSTALLED_APPS = [
# ...
'djangomako',
'makoApp',
# ...
]
TEMPLATES = [
# ...
{
'BACKEND': 'djangomako.backends.MakoBackend',
'NAME': 'mako',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
},
# ...
]

Next step is to adjust djangomako package for our project because it has old import to static to fix it we must find in our virtual env package djangomako ease way to do this is run the project by command python manage.py run server it will throw an error and in one line will be the file where wrong import is situated when we cltr + click in VS it will show this file and allowed us to fix the problem:

old import in backends.py
from django.contrib.staticfiles.templatetags.staticfiles import static
proper import for django 3.0:
from django.templatetags.static import static

Now when we start the local server all will goes properly. When we want to have full control over this package we can create folder with init in the root directory and copy backends.py it will work as a python module.

Next step is to adjust URLs in makoProject/urls.py:

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

And next in makoApp/urls.py:

from django.contrib import admin
from django.urls import path,include

from .views import ClassBasedView
urlpatterns = [
path('', ClassBasedView.as_view(), name='home'),
]

Next makoApp/views.py

The last thing is to create templates directory in the root of our project and create a file home.mako with content:

Now when we start the project with python manage.py run server in the browser will see context data and output from the python function process in the template.

Complete project:

Djangomako package:

--

--