Creating a Django HTMX Project
Requirements
Firstly install the required dependencies.
Python 3
apt-get update -y
apt-get install git python3 python3-pip -y
DBMS
You may also want to install a DBMS, we recommend PostgreSQL:
apt-get update -y
apt-get install postgresql libpq-dev -y
Create the Project Environment
mkdir django_htmx_project
cd django_htmx_project
python3 -m venv .
Install PIP Requirements
pip install django django-admin django-htmx
Setup Django
Once our basic dependencies have been installed, we can proceed to:
- Initialize the Django Project.
- Setup the
template
andstatic
directories. - Add HTMX.
Initialize Project with Django Admin
django-admin startproject core
# Move everything in core initialization one dir up
mv core/* . 2>/dev/null
mv core/core/* core/
rmdir core/core/
# Fix Parent BASEDIR
sed -i "s/parent.parent/parent/g" core/settings.py
Adding Django HTMX
Add the app
and middleware
, along with your core
app module:
# File: core/settings.py
INSTALLED_APPS = [
...,
"django_htmx",
"core",
...,
]
MIDDLEWARE = [
...,
"django_htmx.middleware.HtmxMiddleware",
...,
]
Freeze Initial Requirements
You may want to freeze your first dependencies.
pip freeze > requirements.txt
Define a Static Directory
Add the following to your settings.py
file.
# core/settings.py
STATICFILES_DIRS = [BASE_DIR / "static"]
Then create the directory
mkdir -p core/static
Add a Templates Directory
Add the commented line to include a directory with templates into your Django app.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
f'{BASE_DIR}/views/templates' # Add this line!
],
'APP_DIRS': True,
'OPTIONS': {...},
},
]
Then create the directory:
mkdir -p core/views/templates
Download HTMX Min JS
After setting up the basic project you’ll need to download the HTMX Min JS.
Source: https://htmx.org/docs/#installing
wget -O core/static/htmx.min.js https://unpkg.com/htmx.org/dist/htmx.min.js
Remember to add the script tag to your main layout/template file.
<script src="{% static 'htmx.min.js' %}" defer></script>
Let the fun begin!
Authors:
- Martín Vilche
- Dylan Blanqué