Skip to main content

Extensions for using Django with htmx.

Project description

https://img.shields.io/github/workflow/status/adamchainz/django-htmx/CI/main?style=for-the-badge https://img.shields.io/codecov/c/github/adamchainz/django-htmx/main?style=for-the-badge https://img.shields.io/pypi/v/django-htmx.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge pre-commit

Extensions for using Django with htmx.

Requirements

Python 3.6 to 3.9 supported.

Django 2.2 to 3.2 supported.


Are your tests slow? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.


Installation

  1. Install with pip:

    python -m pip install django-htmx
  2. Add django-htmx to your INSTALLED_APPS:

    INSTALLED_APPS = [
        ...,
        "django_htmx",
        ...,
    ]
  3. Add the middleware:

    MIDDLEWARE = [
        ...,
        "django_htmx.middleware.HtmxMiddleware",
        ...,
    ]
  4. (Optional) Add the extension script to your template, as documented below.

Example app

See the example app in the example/ directory of the GitHub repository for usage of django-htmx.

Reference

Extension Script

django-htmx comes with a small JavaScript extension for htmx’s behaviour. Currently the extension only includes a debug error handler, documented below.

The script is served as a static file called django-htmx.js, but you shouldn’t reference it directly. Instead, use the included template tags, for both Django and Jinja templates. You probably want to include the relevant template tag after your htmx script tag.

For Django Templates, load and use the template tag:

{% load django_htmx %}
{% django_htmx_script %}

For Jinja Templates, you need to perform two steps. First, load the tag function into the globals of your custom environment:

# myproject/jinja2.py
from jinja2 import Environment
from django_htmx.jinja import django_htmx_script


def environment(**options):
    env = Environment(**options)
    env.globals.update({
        # ...
        'django_htmx_script': django_htmx_script,
    })
    return env

Second, call the function in your base template:

{{ django_htmx_script() }}

Debug Error Handler

htmx’s default behaviour when encountering an HTTP error is to discard the response. This can make it hard to debug errors in development.

The django-htmx script includes an error handler that’s active when debug mode is on. The handler detects responses with 404 and 500 status, codes and replaces the page with their content. This change allows you to debug with Django’s default error responses as you would for a non-htmx request.

See this in action in the “Error Demo” section of the example app.

django_htmx.middleware.HtmxMiddleware

This middleware attaches request.htmx, an instance of HtmxDetails.

See it action in the “Middleware Tester” section of the example app.

django_htmx.middleware.HtmxDetails

This class provides shortcuts for reading the htmx-specific request headers.

__bool__(): bool

True if the request was made with htmx, otherwise False. This is based on the presence of the HX-Request header.

This allows you to switch behaviour for requests made with htmx like so:

def my_view(request):
    if request.htmx:
        template_name = "partial.html"
    else:
        template_name = "complete.html"
    return render(template_name, ...)

current_url: str | None

The current URL of the browser, or None for non-htmx requests. Based on the HX-Current-URL header.

history_restore_request: bool

True if the request is for history restoration after a miss in the local history cache. Based on the HX-History-Restore-Request header.

prompt: str | None

The user response to hx-prompt if it was used, or None.

target: str | None

The id of the target element if it exists, or None. Based on the HX-Target header.

trigger: str | None

The id of the triggered element if it exists, or None. Based on the HX-Trigger header.

trigger_name: str | None

The name of the triggered element if it exists, or None. Based on the HX-Trigger-Name header.

triggering_event: Any | None

The deserialized JSON representtation of the event that triggered the request if it exists, or None. This header is set by the event-header htmx extension, and contains details of the DOM event that triggered the request.

django_htmx.http.HttpResponseStopPolling: type[HttpResponse]

When using a polling trigger, htmx will stop polling when it encounters a response with the special HTTP status code 286. HttpResponseStopPolling is a custom response class with that status code.

For example:

from django_htmx.http import HttpResponseStopPolling

def my_pollable_view(request):
    if event_finished():
        return HttpResponseStopPolling()
    ...

django_htmx.http.HTMX_STOP_POLLING: int

A constant for the HTTP status code 286, for use with e.g. Django’s render shortcut.

from django_htmx.http import HTMX_STOP_POLLING

def my_pollable_view(request):
    if event_finished():
        return render("event-finished.html", status=HTMX_STOP_POLLING)
    ...

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-htmx-1.2.1.tar.gz (10.1 kB view details)

Uploaded Source

Built Distribution

django_htmx-1.2.1-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file django-htmx-1.2.1.tar.gz.

File metadata

  • Download URL: django-htmx-1.2.1.tar.gz
  • Upload date:
  • Size: 10.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.6.1 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.2 CPython/3.9.6

File hashes

Hashes for django-htmx-1.2.1.tar.gz
Algorithm Hash digest
SHA256 7b36c0d9a9c056bdca8f26b8a7ecab28c58bae0a3feb76c3e58cdf04d8a25d79
MD5 96e3d1d2f94878b09fc5fbd5711dd231
BLAKE2b-256 fa491e6aa050a7e912bc9fdc8ef1745bebeba62805a8c8360408a8c4eec9d4de

See more details on using hashes here.

File details

Details for the file django_htmx-1.2.1-py3-none-any.whl.

File metadata

  • Download URL: django_htmx-1.2.1-py3-none-any.whl
  • Upload date:
  • Size: 7.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.6.1 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.2 CPython/3.9.6

File hashes

Hashes for django_htmx-1.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 fbdadff14db8ded117b7a46a92f256216e9edcc960cbf26a522af0cd6189731d
MD5 ca9f3d0b1e2c8d6aad3e62b277b41173
BLAKE2b-256 9fbae99b9be53ad02ddc9baa0352594e54a2fec3cb92e5283343e8711b803f78

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page