Create a django custom app template
I was building my own Django project template and I asked myself if it would be possible to create a custom app template for my apps when running the command
python manage.py startapp
It turned out, obviously, it was possible.
The goal is to get the following file structure for a new created django app:
myapp/
βββ admin.py
βββ apps.py
βββ __init__.py
βββ migrations
β βββ __init__.py
βββ models.py
βββ signals.py
βββ templates
βββ tests.py
βββ urls.py
βββ views.py
How can we do that? Let me explain it here shortly.
Copy first
Django has its own apptemplate located at _django/conf/app_template.
So just copy that app_template folder into your working directory.
cp -r venv/lib/python3.8/site-packages/django/conf/app_template/ app_template/
In my case, I am using a Linux distro (Ubuntu 22.04). This means I can use the copy command cp -r
to copy the folder from my virtual environment venv to my current working directory.
Custom files or folders
Once you have your app_template folder in your working directory, you could:
- Modify the content of the *.py-tpl
- Add more files, such as signals.py-tpl or urls.py-tpl
- Add folders. For instance app_template/templates for your HTML templates or app_template/static for your static files (JS, css, images).
I prefer deleting what I don't need than adding what I need. Therefore, I like to add some files to the app_template folder that normally I need when a new app is created.
Here are some.
Adding urls.py-tpl with the imports and the variable urlpatterns
will save some seconds, or it will keep you away from frustration because of repetitive tasks.
# urls.py-tpl
from __future__ import annotations
from django.urls import path
urlpatterns = [
]
And I also created the signals.py-tpl file with a modification on the file apps.py-tpl
# signals.py-tpl
from __future__ import annotations
# apps.py-tpl
from __future__ import annotations
from django.apps import AppConfig
class {{ camel_case_app_name }}Config(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = '{{ app_name }}'
def ready(self):
from . import signals # noqa
An example of an app_template folder structure:
app_template/
βββ admin.py-tpl
βββ apps.py-tpl
βββ __init__.py-tpl
βββ migrations
β βββ __init__.py-tpl
βββ models.py-tpl
βββ signals.py-tpl
βββ templates
βββ tests.py-tpl
βββ urls.py-tpl
βββ views.py-tpl
Run the command now
Now just run the command but point out to your custom app_template folder specifying it on the --template
argument:
python manage.py startapp myapp --template=app_template
Check out your app now!
myapp/
βββ admin.py
βββ apps.py
βββ __init__.py
βββ migrations
β βββ __init__.py
βββ models.py
βββ signals.py
βββ templates
βββ tests.py
βββ urls.py
βββ views.py
Source code
You can find the whole source code under my GitHub account:
π» github.com/ramiboutas/my-django-project-template/