Django Partial Render with Loading Element with HTMX

Adi Ramadhan
2 min readApr 12, 2024

Reference and

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 migrate

Step 2: Create Django Apps
Create apps: python startapp myapp

Step 3: Project Setting: Register Apps, Set Templates Folder (myproject/


'myapp', #updated


'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">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<h1>Index Page</h1>

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

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

<script src=""></script>
<p>Element 1: Faster load.</p>
<p>Element 2: Long running load.</p>

Step 5: Create Function Views myapp/

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/

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/

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

urlpatterns = [
path('', include('myapp.urls')), #updated

Step 9: Run Server and Testing
Run Server: python runserver