Django Partial Render with Loading Element with HTMX

Adi Ramadhan
2 min readApr 12, 2024

--

Reference https://www.djangoproject.com/ and https://htmx.org/

partially render

Case: Some element has long running process, need render html page partially.

Step 1: Preparation, Create Django Project, Inital Migration
create virtualenv: virtualenv venv
start virtualenv: venv/Scripts/activate
install Django in virtualenv: pip install django==4.2
Create Django: django-admin startproject myproject
Go to myproject folder: cd myproject
Initial Migration: python manage.py migrate

Step 2: Create Django Apps
Create apps: python manage.py startapp myapp

Step 3: Project Setting: Register Apps, Set Templates Folder (myproject/settings.py)

...

INSTALLED_APPS = [
...
'myapp', #updated
]

...

TEMPLATES = [
...
'DIRS': [Path(BASE_DIR, 'templates')], #updated
...
]


...

Step 4: Create HTML Files in Templates Folder

Create templates folder in main app

Create templates/index.html, templates/element1.html, templates/element2.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
</head>
<body>
<h1>Index Page</h1>

<div hx-get="{% url 'element1' %}" hx-trigger="load">
<p >loading...</p>
</div>

<div hx-get="{% url 'element2' %}" hx-trigger="load">
<p >loading...</p>
</div>

<script src="https://unpkg.com/htmx.org@1.9.11"></script>
</body>
</html>
<p>Element 1: Faster load.</p>
<p>Element 2: Long running load.</p>

Step 5: Create Function Views myapp/views.py

from django.shortcuts import render
import time

# Create your views here.
def index(request):
return render(request, 'index.html', {})

def element1(request):
# faster running process simulation
time.sleep(2) # 2s sleep
return render(request, 'element1.html', {})

def element2(request):
# long running process simulation
time.sleep(5) # 5s sleep
return render(request, 'element2.html', {})

Step 8: Setup URLS

Create myapp/urls.py


from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
path('element1/', views.element1, name='element1'),
path('element2/', views.element2, name='element2'),
]

Update myproject/urls.py

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

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')), #updated
]

Step 9: Run Server and Testing
Run Server: python manage.py runserver
Testing: http://127.0.0.1:8000/

--

--

Adi Ramadhan
Adi Ramadhan

No responses yet