Skip to content
Aditya Bhalsod
← Web
WebIntermediate

Building Django Project and App Templates With .py-tpl Files

How startproject and startapp --template render files, shown with my django-rest-api-template: the .py-tpl suffix, the variables it uses and the DRF settings it adds.

  • #django
  • #django-rest-framework
  • #project-template
  • #python
Contents
  1. What the two commands do
  2. Why the files end in .py-tpl
  3. Which variables the files use
  4. What it sets up beyond the default skeleton
  5. Problems I would fix before reusing it
  6. When a template beats a copied repo

django-rest-api-template is a Django REST Framework starter that I wrote as two template directories instead of a normal project: project_template/ for django-admin startproject --template and app_template/ for startapp --template. It pins Django 3.0.5 in requirements.txt, so read it as an older template that needs updating, not a finished one. The README's own TODO list says Docker, Celery, cloud storage and social login are not there.

The interesting part is not DRF. It is how Django's template commands decide which files to render and which names to replace, and what that means for the files you ship.

What the two commands do

Both commands copy a directory, rename some paths and run some files through Django's template engine. The README gives the commands:

Bash
django-admin.py startproject --template='~/project_template' --extension py,yaml,md <project_name>

cd <project_name>
python manage.py startapp --template='~/app_template' <app_name>

~/project_template assumes you copied the directory to your home folder. The --extension flag matters. Django renders only py files by default, and two files here use a variable without being Python: the entrypoint: line in app.yaml and the template's own README.md. Leave out yaml,md and the literal text {{ project_name }} ends up in the generated project.

Why the files end in .py-tpl

Look at app_template/models.py-tpl:

Python
from base.models import BaseModel
from django.db import models

class {{camel_case_app_name}}(BaseModel):
    pass

That is not valid Python. If the file were called models.py, anything that walks the repository would choke on it: a formatter such as black (pinned in requirements.txt), a linter, or byte compilation. Django handles this with a naming rule. When it copies a template, it renames .py-tpl to .py. The suffix means "render me first, treat me as Python afterwards".

Not every file needs it. base/, account/, documentation.py and the environment modules are plain .py files because they use no variables. They still go through the template engine, since py is in the default extension list, so a stray {{ or {% in one of them would be rendered. None of them has one.

Which variables the files use

Django hands the templates a fixed set of variables. These are the ones this repo uses:

VariableUsed inBecomes
project_namemanage.py-tpl, wsgi.py-tpl, asgi.py-tpl, common.py-tpl, app.yamlThe settings module, ROOT_URLCONF, WSGI_APPLICATION and the gunicorn entrypoint
docs_version, django_versioncommon.py-tpl, urls.py-tpl, wsgi.py-tpl, asgi.py-tplDocumentation links and the version in a header comment
app_nameapps.py-tpl, urls.py-tpl, __init__.py-tplThe app's name and its router basename
camel_case_app_namemodels, serializers, views, admin, apps and urlsClass names such as OrderItem for an app called order_item

The default skeleton also receives a generated secret_key and writes it into settings.py. Nothing here uses it. common.py-tpl reads SECRET_KEY from the environment instead.

What it sets up beyond the default skeleton

The big change is the settings layout. manage.py-tpl sets DJANGO_SETTINGS_MODULE to {{ project_name }}, the package itself, so project_name/__init__.py is the settings module. This is a trimmed version of it:

Python
from dotenv import load_dotenv

load_dotenv()

import os

from .common import *

if os.getenv("ENVIRONMENT") == "local":  # local development
    from .local import *  # noqa
elif os.getenv("ENVIRONMENT") == "staging":  # staging development
    from .staging import *
else:  # production
    from .production import *

local.py ships as local.py.example and is git-ignored, so you create it yourself. common.py-tpl holds the shared settings and reads SECRET_KEY, HOSTS and the Postgres connection from environment variables. The README tells you to add your domain to ALLOWED_HOSTS in settings.py, but there is no settings.py. The value comes from the HOSTS variable.

The DRF block replaces the defaults with token, session and basic authentication, IsAuthenticated plus DjangoModelPermissions, JSON and template-HTML renderers, AcceptHeaderVersioning and a custom exception handler from base/exceptions.py. The template also adds an email-based User model in account, Swagger and ReDoc through drf-yasg, and a seed command that creates an admin from ADMIN_EMAIL and ADMIN_PASSWORD.

The generated app builds on that base package:

Python
from account.permission import BaseModelPermissions
from base.views import ModelViewSet

class {{ camel_case_app_name }}ViewSet(ModelViewSet):
    serializer_class = {{ camel_case_app_name }}Serializers
    permission_classes = (BaseModelPermissions,)
    queryset = {{ camel_case_app_name }}.objects.all()

So app_template only works inside a project made from project_template. After startapp you still add the app to PROJECT_APP in common.py and include its urls.py yourself.

Problems I would fix before reusing it

  • .env.example lists ENVIRONMENTS, but __init__.py reads ENVIRONMENT. A copy of the example filled in as written falls through to the production module.
  • DEBUG comes from os.getenv as a string, so DEBUG=False in the environment is still truthy.
  • app_template/admin.py-tpl uses @admin.register but never imports admin, so a freshly generated app fails on import.
  • account/permission.py calls viewable(), editable() and deletable() on querysets, and nothing in the repo defines them. I did not run it, but I expect retrieve, update and delete to fail.
  • It targets Django 3.0. documentation.py imports django.conf.urls.url and account/models.py imports ugettext_lazy, and both were removed in Django 4.0.

When a template beats a copied repo

A template fits when you start several projects of the same shape and want the project name and Django version filled in for you. It stops working at the first upgrade, because nothing in this repo generates a project and checks the result. If I used it again, I would generate one in CI and run manage.py check before trusting any change.

Found this useful? Share it with your team.

Keep reading

More from Web and beyond