Django HTMX

1.27.0 · active · verified Sun Apr 12

django-htmx is a Python package that provides extensions for integrating Django with htmx. It simplifies building dynamic and interactive web applications by offering middleware, template tags, and HTTP response utilities, allowing developers to leverage htmx's capabilities without writing extensive JavaScript. The library is actively maintained with a regular release cadence, ensuring compatibility with recent Django and Python versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `django-htmx` and create a basic view that responds differently to HTMX requests. It includes necessary `settings.py` configurations, an example view using `request.htmx`, and a corresponding HTML template snippet. Remember to include the `htmx.org` JavaScript library (e.g., via CDN) and configure CSRF token handling for POST requests.

import os
from django.shortcuts import render
from django.http import HttpResponse

# settings.py additions
# INSTALLED_APPS = [
#     ...,
#     'django_htmx',
# ]
# MIDDLEWARE = [
#     ...,
#     'django_htmx.middleware.HtmxMiddleware',
# ]

def my_view(request):
    if request.htmx:
        # This branch handles HTMX requests
        return HttpResponse("<div>Updated content from HTMX!</div>")
    else:
        # This branch handles initial page load or regular requests
        context = {'initial_message': 'Click the button below to update!'}
        return render(request, 'my_template.html', context)

# my_template.html (within your templates directory, inheriting a base.html)
# Assuming base.html includes the htmx.org script and {% django_htmx_script %}
# and has <body hx-headers='{"x-csrftoken": "{{ csrf_token }}"}'>
#
# {% load django_htmx %}
# <!DOCTYPE html>
# <html lang="en">
# <head>
#     <meta charset="UTF-8">
#     <title>Django HTMX Demo</title>
#     <script src="https://unpkg.com/htmx.org@1.9.10"></script> <!-- or self-host -->
#     {% django_htmx_script %}
# </head>
# <body hx-headers='{"x-csrftoken": "{{ csrf_token }}"}'>
#     <div id="content">{{ initial_message }}</div>
#     <button hx-get="/my-htmx-view/" hx-target="#content" hx-swap="innerHTML">Load HTMX Content</button>
# </body>
# </html>

# urls.py addition (example)
# from django.urls import path
# from . import views
#
# urlpatterns = [
#     path('my-htmx-view/', views.my_view, name='my_htmx_view'),
# ]

view raw JSON →