### Download htmx extension script using curl
Source: https://django-htmx.readthedocs.io/en/latest/tips.html
This command downloads the WebSocket extension script (ws.min.js) from an unpkg.com URL and saves it to the specified static directory within the example project. This method ensures local serving of the extension.
```bash
curl -L https://unpkg.com/htmx-ext-ws/dist/ws.min.js -o example/static/htmx-ext-ws.min.js
```
--------------------------------
### Install django-htmx via pip
Source: https://django-htmx.readthedocs.io/en/latest/_sources/installation.rst.txt
Use the pip package manager to install the django-htmx library into your Python environment.
```shell
python -m pip install django-htmx
```
--------------------------------
### Partial Rendering with django-template-partials
Source: https://django-htmx.readthedocs.io/en/latest/tips.html
This example shows how to use the django-template-partials package to render only specific sections of a template for htmx requests. The `{% partialdef %}` tag defines a reusable section, and the view logic conditionally appends the partial name to the template name for htmx requests.
```html
{% extends "_base.html" %}
{% load partials %}
{% block main %}
Countries
...
{% partialdef country-table inline %}
...
{% for country in countries %}
...
{% endfor %}
{% endpartialdef %}
...
{% endblock main %}
```
```python
from django.shortcuts import render
from example.models import Country
def country_listing(request):
template_name = "countries.html"
if request.htmx:
template_name += "#country-table"
countries = Country.objects.all()
return render(
request,
template_name,
{
"countries": countries,
},
)
```
--------------------------------
### Use HTMX Current URL for Redirects in Django
Source: https://django-htmx.readthedocs.io/en/latest/_sources/middleware.rst.txt
This example shows how to use the 'request.htmx.current_url_abs_path' attribute in a Django view to construct a redirect URL. It's particularly useful for redirecting users after an action, maintaining their context.
```python
from django.http import HttpResponseClientRedirect
def my_view(request):
if not sudo_mode_active(request):
next_url = request.htmx.current_url_abs_path or ""
return HttpResponseClientRedirect(f"/activate-sudo/?next={next_url}")
```
--------------------------------
### Check for HTMX Request in Django View
Source: https://django-htmx.readthedocs.io/en/latest/_sources/middleware.rst.txt
This example illustrates a basic Django view that checks if a request was made using HTMX. It conditionally renders a different template based on the presence of the 'request.htmx' attribute, allowing for dynamic content delivery.
```python
from django.shortcuts import render
def my_view(request):
if request.htmx:
template_name = "partial.html"
else:
template_name = "complete.html"
return render(request, template_name, ...)
```
--------------------------------
### Set Vary Header for Cacheable Responses in Django
Source: https://django-htmx.readthedocs.io/en/latest/_sources/middleware.rst.txt
This example demonstrates how to set the 'Vary' header for cacheable responses when using HTMX in Django views. It ensures that cached responses are correctly served based on the 'HX-Request' header, preventing issues with stale content.
```python
from django.shortcuts import render
from django.views.decorators.cache import cache_control
from django.views.decorators.vary import vary_on_headers
@cache_control(max_age=300)
@vary_on_headers("HX-Request")
def my_view(request):
if request.htmx:
template_name = "partial.html"
else:
template_name = "complete.html"
return render(request, template_name, ...)
```
--------------------------------
### Swap base templates for partial rendering
Source: https://django-htmx.readthedocs.io/en/latest/_sources/tips.rst.txt
Demonstrates a manual approach to partial rendering by dynamically selecting a base template in the view based on whether the request originated from htmx.
```python
@require_GET
def partial_rendering(request: HttpRequest) -> HttpResponse:
if request.htmx:
base_template = "_partial.html"
else:
base_template = "_base.html"
return render(
request,
"page.html",
{
"base_template": base_template,
},
)
```
--------------------------------
### Configure Django Settings
Source: https://django-htmx.readthedocs.io/en/latest/_sources/installation.rst.txt
Register the django-htmx application in your INSTALLED_APPS list and optionally add the HtmxMiddleware to your MIDDLEWARE configuration.
```python
INSTALLED_APPS = [
...,
"django_htmx",
...,
]
MIDDLEWARE = [
...,
"django_htmx.middleware.HtmxMiddleware",
...,
]
```
--------------------------------
### Performing Boosted Requests with HttpResponseLocation
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Illustrates using HttpResponseLocation to send the HX-Location header, which instructs htmx to perform a client-side boosted request.
```python
from django_htmx.http import HttpResponseLocation
def wait_for_completion(request, action_id):
...
if action.completed:
return HttpResponseLocation(f"/action/{action.id}/completed/")
...
```
--------------------------------
### Implement partial rendering with django-template-partials
Source: https://django-htmx.readthedocs.io/en/latest/_sources/tips.rst.txt
Shows how to define a partial section in a Django template using the partials library and conditionally render that specific partial in a view when an htmx request is detected.
```django
{% partialdef country-table inline %}
...
{% for country in countries %}
...
{% endfor %}
{% endpartialdef %}
```
```python
def country_listing(request):
template_name = "countries.html"
if request.htmx:
template_name += "#country-table"
countries = Country.objects.all()
return render(
request,
template_name,
{
"countries": countries,
},
)
```
--------------------------------
### HttpResponseLocation
Source: https://django-htmx.readthedocs.io/en/latest/_sources/http.rst.txt
Sends an HX-Location header to trigger a boosted client-side request.
```APIDOC
## HttpResponseLocation
### Description
Used to trigger a client-side 'boosted' request to a specific location.
### Parameters
- **redirect_to** (string) - Required - The target URL.
- **source, event, target, swap, select, values, headers** - Optional - Configuration for the boosted request.
### Request Example
```python
return HttpResponseLocation(f"/action/{action.id}/completed/")
```
```
--------------------------------
### push_url
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Sets the HX-Push-Url header to push a new URL into the browser's history.
```APIDOC
## push_url
### Description
Sets the `HX-Push-Url` header of `response` and returns it. This header makes htmx push the given URL into the browser location history.
### Method
N/A (Function within Django)
### Endpoint
N/A (Function within Django)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```python
from django_htmx.http import push_url
def leaf(request, leaf_id):
...
if leaf is None:
response = branch(request, leaf.branch)
return push_url(response, f"/branch/{leaf.branch.id}")
...
```
### Response
#### Success Response (200)
HttpResponse with `HX-Push-Url` header set.
#### Response Example
N/A (Function modifies an existing HttpResponse)
```
--------------------------------
### Triggering Client-Side Redirects with HttpResponseClientRedirect
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Demonstrates using HttpResponseClientRedirect to instruct the htmx client to perform a redirect by sending the HX-Redirect header.
```python
from django_htmx.http import HttpResponseClientRedirect
def sensitive_view(request):
if not sudo_mode.active(request):
return HttpResponseClientRedirect("/activate-sudo-mode/")
...
```
--------------------------------
### Triggering Page Refresh with HttpResponseClientRefresh
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Shows how to use HttpResponseClientRefresh to trigger a full page reload on the client side via the HX-Refresh header.
```python
from django_htmx.http import HttpResponseClientRefresh
def partial_table_view(request):
if page_outdated(request):
return HttpResponseClientRefresh()
...
```
--------------------------------
### Including the django-htmx script
Source: https://django-htmx.readthedocs.io/en/latest/_sources/template_tags.rst.txt
This snippet shows how to include the main django-htmx script in your HTML template. It also demonstrates how to pass a CSP nonce if needed.
```APIDOC
## Including the django-htmx script
### Description
Include the main django-htmx JavaScript file in your HTML template using the `django_htmx_script` template tag. If you are using Content Security Policy (CSP) with nonces, you can pass the nonce value to the template tag.
### Template Tag Usage
```jinja
{{ django_htmx_script() }}
```
### Template Tag Usage with CSP Nonce
```jinja
{{ django_htmx_script(nonce=csp_nonce) }}
```
### Parameters
#### Template Tag Parameters
- **nonce** (string) - Optional - The CSP nonce to be added to the script tag.
```
--------------------------------
### HtmxMiddleware and HtmxDetails
Source: https://django-htmx.readthedocs.io/en/latest/middleware.html
Overview of the HtmxMiddleware which enables request.htmx access and the HtmxDetails class which provides properties to inspect htmx request headers.
```APIDOC
## HtmxMiddleware
### Description
The `HtmxMiddleware` attaches an instance of `HtmxDetails` to the Django `request` object as `request.htmx`. This allows views to detect if a request originated from htmx and access specific header information.
### Usage
Add `django_htmx.middleware.HtmxMiddleware` to your `MIDDLEWARE` setting in `settings.py`.
## HtmxDetails Properties
### Description
`HtmxDetails` provides access to htmx-specific headers sent by the client.
- **__bool__()** (bool) - Returns True if the request was made with htmx (HX-Request header).
- **boosted** (bool) - True if the request came from an element with hx-boost.
- **current_url** (str|None) - The URL the request was made from.
- **current_url_abs_path** (str|None) - The absolute path of the current URL.
- **history_restore_request** (bool) - True if the request is for history restoration.
- **prompt** (str|None) - User response to hx-prompt.
- **target** (str|None) - ID of the target element (HX-Target).
- **trigger** (str|None) - ID of the triggered element (HX-Trigger).
- **trigger_name** (str|None) - Name of the triggered element (HX-Trigger-Name).
- **triggering_event** (Any|None) - Deserialized JSON of the event that triggered the request.
### Example
```python
def my_view(request):
if request.htmx:
return render(request, "partial.html")
return render(request, "complete.html")
```
```
--------------------------------
### Partial Rendering by Swapping Base Template
Source: https://django-htmx.readthedocs.io/en/latest/tips.html
This technique involves conditionally selecting a different base template in the Django view based on whether the request is an htmx request. This allows for minimal rendering of only the necessary content for htmx updates, while full page loads use a comprehensive base template.
```python
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from django.views.decorators.http import require_GET
@require_GET
def partial_rendering(request: HttpRequest) -> HttpResponse:
if request.htmx:
base_template = "_partial.html"
else:
base_template = "_base.html"
...
return render(
request,
"page.html",
{
"base_template": base_template,
# ...
},
)
```
```html
{% extends base_template %}
{% block main %}
...
{% endblock %}
```
```html
...
{% block main %}{% endblock %}
```
```html
{% block main %}{% endblock %}
```
--------------------------------
### Handle Boosted HTMX Requests in Django
Source: https://django-htmx.readthedocs.io/en/latest/_sources/middleware.rst.txt
This Django view snippet demonstrates how to detect and handle requests made from an element with the 'hx-boost' attribute. It allows for specific behavior when HTMX boosting is active, enhancing user experience.
```python
def my_view(request):
if request.htmx.boosted:
# do something special
...
return render(request, ...)
```
--------------------------------
### Render HTMX and Extension Scripts in Jinja Templates
Source: https://django-htmx.readthedocs.io/en/latest/_sources/template_tags.rst.txt
Renders both the vendored HTMX script and the django-htmx extension script for debugging in Jinja templates. The extension script is only included when settings.DEBUG is True. It supports minified and non-minified HTMX versions and CSP nonces. Requires loading the functions into the Jinja environment.
```python
from jinja2 import Environment
from django_htmx.jinja import htmx_script
def environment(**options):
env = Environment(**options)
env.globals.update(
{
# ...
"htmx_script": htmx_script,
}
)
return env
```
```jinja
{% load django_htmx %}
...
{{ htmx_script() }}
...
```
```jinja
{{ htmx_script(minified=False) }}
```
```jinja
{{ htmx_script(nonce=csp_nonce) }}
```
--------------------------------
### push_url / replace_url
Source: https://django-htmx.readthedocs.io/en/latest/_sources/http.rst.txt
Functions to manage browser history by setting HX-Push-Url or HX-Replace-Url headers.
```APIDOC
## push_url / replace_url
### Description
These functions modify the browser's location history by setting the HX-Push-Url or HX-Replace-Url headers on the response.
### Parameters
#### Request Body
- **response** (HttpResponse) - Required - The Django response object to modify.
- **url** (string|bool) - Required - The relative URL to push/replace, or False to prevent history updates.
### Request Example
```python
from django_htmx.http import push_url
return push_url(response, "/new-url/")
```
```
--------------------------------
### HTMX HTTP Response Helpers
Source: https://django-htmx.readthedocs.io/en/latest/genindex.html
Helper classes for returning specific HTMX-compatible HTTP responses.
```APIDOC
## HTMX HTTP Response Helpers
### Description
These classes simplify the creation of HTTP responses tailored for HTMX interactions, such as redirects, refreshes, and polling control.
### Classes
- **HttpResponseClientRedirect** (class) - Triggers a client-side redirect.
- **HttpResponseClientRefresh** (class) - Triggers a client-side page refresh.
- **HttpResponseLocation** (class) - Instructs the client to navigate to a new URL.
- **HttpResponseStopPolling** (class) - Stops HTMX polling.
```
--------------------------------
### Configure Django Base Template
Source: https://django-htmx.readthedocs.io/en/latest/_sources/installation.rst.txt
Load the django_htmx template tags and include the htmx script in your base template. Also, ensure the CSRF token is included in the hx-headers attribute for secure POST requests.
```django
{% load django_htmx %}
...
{% htmx_script %}
...
```
--------------------------------
### Include Django HTMX Script with CSP Nonce
Source: https://django-htmx.readthedocs.io/en/latest/_sources/template_tags.rst.txt
This snippet shows how to include the django-htmx JavaScript in your HTML template. It demonstrates the basic usage and how to pass a CSP nonce for security.
```jinja
{{ django_htmx_script() }}
{{ django_htmx_script(nonce=csp_nonce) }}
```
--------------------------------
### Push URL with HTMX
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Uses push_url to update the browser's location history via the HX-Push-Url header. It takes an HttpResponse object and a URL string as inputs.
```python
from django_htmx.http import push_url
def leaf(request, leaf_id):
...
if leaf is None:
response = branch(request, branch=leaf.branch)
return push_url(response, f"/branch/{leaf.branch.id}")
```
--------------------------------
### Render HTMX Script Tag in Jinja Templates
Source: https://django-htmx.readthedocs.io/en/latest/template_tags.html
Renders both the vendored htmx script and the django-htmx extension script (if DEBUG is True) in Jinja environments. Supports minification control and CSP nonces.
```python
from jinja2 import Environment
from django_htmx.jinja import htmx_script
def environment(**options):
env = Environment(**options)
env.globals.update({
# ...
"htmx_script": htmx_script,
})
return env
```
```jinja
{{ htmx_script() }}
```
```jinja
{{ htmx_script(minified=False) }}
```
```jinja
{{ htmx_script(nonce=csp_nonce) }}
```
--------------------------------
### Implement HtmxMiddleware for Django
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/middleware.html
The HtmxMiddleware class handles both synchronous and asynchronous request processing. It attaches an HtmxDetails instance to the request object, allowing developers to inspect HTMX headers.
```python
class HtmxMiddleware:
sync_capable = True
async_capable = True
def __init__(self, get_response):
self.get_response = get_response
self.async_mode = iscoroutinefunction(self.get_response)
def __call__(self, request):
if self.async_mode:
return self.__acall__(request)
request.htmx = HtmxDetails(request)
return self.get_response(request)
async def __acall__(self, request):
request.htmx = HtmxDetails(request)
return await self.get_response(request)
```
--------------------------------
### HttpResponseClientRefresh
Source: https://django-htmx.readthedocs.io/en/latest/_sources/http.rst.txt
Triggers a full page reload in the browser via the HX-Refresh header.
```APIDOC
## HttpResponseClientRefresh
### Description
Forces the browser to reload the page when received by HTMX.
### Method
N/A (Response Class)
### Request Example
```python
return HttpResponseClientRefresh()
```
```
--------------------------------
### reselect
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Sets the HX-Reselect header to override the HTMX selection of content to swap.
```APIDOC
## reselect
### Description
Sets the `HX-Reselect` header of `response` and returns it. This header overrides the selection of the response that htmx will swap into the target.
### Method
N/A (Function within Django)
### Endpoint
N/A (Function within Django)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```python
# Example usage for reselect is not provided in the source text.
```
### Response
#### Success Response (200)
HttpResponse with `HX-Reselect` header set.
#### Response Example
N/A (Function modifies an existing HttpResponse)
```
--------------------------------
### reswap
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Sets the HX-Reswap header to override the HTMX swap method.
```APIDOC
## reswap
### Description
Sets the `HX-Reswap` header of `response` and returns it. This header overrides the swap method that htmx will use.
### Method
N/A (Function within Django)
### Endpoint
N/A (Function within Django)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```python
from django.shortcuts import render
from django_htmx.http import reswap
def employee_table_row(request):
response = render(...)
if employee.is_boss:
reswap(response, "afterbegin")
return response
```
### Response
#### Success Response (200)
HttpResponse with `HX-Reswap` header set.
#### Response Example
N/A (Function modifies an existing HttpResponse)
```
--------------------------------
### Trigger Client Event in Django View
Source: https://django-htmx.readthedocs.io/en/latest/_sources/http.rst.txt
This Python code snippet demonstrates how to render an HTML template and then trigger a client-side event using HTMX. It specifically shows how to send custom event data to the frontend after a response is rendered. Dependencies include Django's render function and a hypothetical `trigger_client_event` utility.
```python
def end_of_long_process(request):
response = render(request, "end-of-long-process.html")
return trigger_client_event(
response,
"showConfetti",
{"colours": ["purple", "red", "pink"]},
after="swap",
)
```
--------------------------------
### Reswap HTMX Content
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Uses reswap to override the default swap method using the HX-Reswap header. It accepts the response and a swap method string.
```python
from django.shortcuts import render
from django_htmx.http import reswap
def employee_table_row(request):
...
response = render(...)
if employee.is_boss:
reswap(response, "afterbegin")
return response
```
--------------------------------
### HttpResponseLocation
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/http.html
Custom HttpResponse class for advanced client-side navigation and updates using HTMX headers.
```APIDOC
## HttpResponseLocation
### Description
This class allows for sophisticated client-side navigation and content updates by setting the `HX-Location` header. It supports specifying the target path, source element, event details, swap method, target element, selection criteria, custom values, and additional headers.
### Method
N/A (Class definition)
### Endpoint
N/A
### Parameters
- **redirect_to** (str) - Required - The target path for the location update.
- **source** (str, optional) - Selector for the triggering element.
- **event** (str, optional) - Name of the event to trigger.
- **target** (str, optional) - Selector for the target element to update.
- **swap** (SwapMethod, optional) - The HTMX swap method to use (e.g., `innerHTML`, `outerHTML`).
- **select** (str, optional) - Selector to specify which part of the response to use.
- **values** (dict[str, str], optional) - Custom values to send with the event.
- **headers** (dict[str, str], optional) - Additional headers to include.
- ***args** - Variable positional arguments passed to the parent class.
- ****kwargs** - Variable keyword arguments passed to the parent class.
### Request Example
N/A
### Response
#### Success Response (200)
- **Headers**: Includes `HX-Location` with a JSON object detailing the navigation/update parameters.
#### Response Example
```http
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
HX-Location: {"path": "/new/content", "target": "#main", "swap": "innerHTML", "event": "loadPage"}
Content-Length: 0
```
```
--------------------------------
### Trigger Client-Side Events
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Uses trigger_client_event to send events to the client via HX-Trigger headers. It supports optional parameters and timing control (receive, settle, swap).
```python
from django.shortcuts import render
from django_htmx.http import trigger_client_event
def end_of_long_process(request):
response = render(request, "end-of-long-process.html")
return trigger_client_event(response, "process-complete", {"id": 123})
```
--------------------------------
### replace_url
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Sets the HX-Replace-Url header to replace the current URL in the browser's location history.
```APIDOC
## replace_url
### Description
Sets the `HX-Replace-Url` header of `response` and returns it. This header causes htmx to replace the current URL in the browser location history.
### Method
N/A (Function within Django)
### Endpoint
N/A (Function within Django)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```python
from django_htmx.http import replace_url
def dashboard(request):
response = render(request, "dashboard.html", ...)
return replace_url(response, "/dashboard/")
```
### Response
#### Success Response (200)
HttpResponse with `HX-Replace-Url` header set.
#### Response Example
N/A (Function modifies an existing HttpResponse)
```
--------------------------------
### Select Content for Swapping with Django HTMX
Source: https://django-htmx.readthedocs.io/en/latest/_sources/http.rst.txt
The `reselect` function sets the `HX-Reselect` header, which allows you to specify a CSS selector for the exact part of the response content that HTMX should use for the swap. This is helpful when the response contains more HTML than needed for the specific swap target.
```python
from django_htmx.http import reselect
# Assuming 'response' is a Django HttpResponse object
# and 'selectori' is a CSS selector string
# reselect(response, selectori)
```
--------------------------------
### HttpResponseClientRedirect
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/http.html
Custom HttpResponse class for client-side redirects using HTMX headers.
```APIDOC
## HttpResponseClientRedirect
### Description
This class creates an HTTP response that instructs the client's browser to redirect to a new URL. It leverages the `HX-Redirect` header for HTMX-driven redirects, overriding the standard `Location` header.
### Method
N/A (Class definition)
### Endpoint
N/A
### Parameters
- **redirect_to** (str) - Required - The URL to redirect the client to.
- ***args** - Variable positional arguments passed to the parent class.
- ****kwargs** - Variable keyword arguments passed to the parent class.
### Request Example
N/A
### Response
#### Success Response (200)
- **Headers**: Includes `HX-Redirect` with the redirect URL.
#### Response Example
```http
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
HX-Redirect: /new/url
Content-Length: 0
```
```
--------------------------------
### Include htmx and extension script in Django template
Source: https://django-htmx.readthedocs.io/en/latest/tips.html
This HTML snippet demonstrates how to load Django htmx tags and include both the main htmx script and a downloaded extension script (htmx-ext-ws.min.js) in a Django base template. The extension script is included after the main htmx script for proper functionality.
```html
{% load django_htmx static %}
...
{% htmx_script %}
...
```
--------------------------------
### reswap Utility
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/http.html
Utility function to change the HTMX swap method for subsequent requests.
```APIDOC
## reswap
### Description
This function sets the `HX-Reswap` header on the response, allowing you to specify a different HTMX swap method for the next AJAX request's response.
### Method
N/A (Function definition)
### Endpoint
N/A
### Parameters
- **response** (_HttpResponse) - Required - The Django HTTP response object to modify.
- **method** (SwapMethod) - Required - The HTMX swap method to apply (e.g., `innerHTML`, `outerHTML`, `none`).
### Request Example
N/A
### Response
#### Success Response (200)
- **Headers**: Includes `HX-Reswap` with the specified swap method.
#### Response Example
```python
from django.http import HttpResponse
from django_htmx.http import reswap
response = HttpResponse()
reswap(response, "none")
# response will have HX-Reswap: none header
```
```
--------------------------------
### reselect Utility
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/http.html
Utility function to specify which part of the HTMX response should be used for updates.
```APIDOC
## reselect
### Description
This function sets the `HX-Reselect` header on the response. It allows you to specify a CSS selector to extract a specific part of the response HTML that will be used for the update, rather than the entire response body.
### Method
N/A (Function definition)
### Endpoint
N/A
### Parameters
- **response** (_HttpResponse) - Required - The Django HTTP response object to modify.
- **selector** (str) - Required - The CSS selector to identify the content to use from the response.
### Request Example
N/A
### Response
#### Success Response (200)
- **Headers**: Includes `HX-Reselect` with the specified CSS selector.
#### Response Example
```python
from django.http import HttpResponse
from django_htmx.http import reselect
response = HttpResponse()
reselect(response, ".user-profile")
# response will have HX-Reselect: .user-profile header
```
```
--------------------------------
### trigger_client_event Utility
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/http.html
Utility function to trigger custom events on the client-side via HTMX headers.
```APIDOC
## trigger_client_event
### Description
This function adds headers (`HX-Trigger`, `HX-Trigger-After-Settle`, or `HX-Trigger-After-Swap`) to the response, allowing you to dispatch custom events on the client-side. These events can optionally carry parameters.
### Method
N/A (Function definition)
### Endpoint
N/A
### Parameters
- **response** (_HttpResponse) - Required - The Django HTTP response object to modify.
- **name** (str) - Required - The name of the custom event to trigger.
- **params** (dict[str, Any], optional) - A dictionary of parameters to send with the event.
- **after** (Literal["receive", "settle", "swap"], optional) - When the event should be triggered. Defaults to `receive`.
- **encoder** (type[json.JSONEncoder], optional) - The JSON encoder to use for parameters. Defaults to `DjangoJSONEncoder`.
### Request Example
N/A
### Response
#### Success Response (200)
- **Headers**: Includes `HX-Trigger`, `HX-Trigger-After-Settle`, or `HX-Trigger-After-Swap` with a JSON object representing the event and its parameters.
#### Response Example
```python
from django.http import HttpResponse
from django_htmx.http import trigger_client_event
response = HttpResponse()
trigger_client_event(response, "myCustomEvent", {"data": "someValue"})
# response will have HX-Trigger: {"myCustomEvent": {"data": "someValue"}} header
trigger_client_event(response, "anotherEvent", after="swap")
# response will have HX-Trigger-After-Swap: {"anotherEvent": {}} header
```
```
--------------------------------
### Push URL with Django HTMX
Source: https://django-htmx.readthedocs.io/en/latest/_sources/http.rst.txt
The `push_url` function modifies the response to include an `HX-Push-Url` header, which tells HTMX to push a new URL onto the browser's location history without triggering a page load. It takes the response object and the URL to push as arguments. If `False` is provided for the URL, history updates are prevented.
```python
from django_htmx.http import push_url
def leaf(request, leaf_id):
...
if leaf is None:
# Directly render branch view
response = branch(request, branch=leaf.branch)
return push_url(response, f"/branch/{leaf.branch.id}")
...
```
--------------------------------
### retarget / reswap / reselect
Source: https://django-htmx.readthedocs.io/en/latest/_sources/http.rst.txt
Functions to override htmx swap behavior by setting HX-Retarget, HX-Reswap, or HX-Reselect headers.
```APIDOC
## retarget / reswap / reselect
### Description
These functions allow fine-grained control over how htmx processes the response by overriding the target element, swap method, or content selector.
### Parameters
#### Request Body
- **response** (HttpResponse) - Required - The Django response object.
- **target/method/selector** (string) - Required - The CSS selector or swap method string.
### Request Example
```python
from django_htmx.http import retarget
return retarget(response, "#target-element")
```
```
--------------------------------
### HTMX Middleware
Source: https://django-htmx.readthedocs.io/en/latest/genindex.html
Middleware for processing HTMX requests and adding details to the request object.
```APIDOC
## HtmxMiddleware
### Description
This middleware processes incoming requests to detect HTMX headers and attaches an `HtmxDetails` object to the request for easy access to HTMX-specific information.
### Class
- **HtmxMiddleware** (class in django_htmx.middleware)
```
--------------------------------
### Stopping Polling with HttpResponseStopPolling and HTMX_STOP_POLLING
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Demonstrates two ways to stop htmx polling: using the specialized HttpResponseStopPolling class or the HTMX_STOP_POLLING status code constant.
```python
from django_htmx.http import HttpResponseStopPolling
def my_pollable_view(request):
if event_finished():
return HttpResponseStopPolling()
...
from django.shortcuts import render
from django_htmx.http import HTMX_STOP_POLLING
def my_pollable_view(request):
if event_finished():
return render(request, "event-finished.html", status=HTMX_STOP_POLLING)
...
```
--------------------------------
### Render Only Django HTMX Extension Script in Jinja Templates
Source: https://django-htmx.readthedocs.io/en/latest/_sources/template_tags.rst.txt
Renders only the django-htmx extension script for debugging in Jinja templates. This is used when HTMX is sourced externally. The script is included only when settings.DEBUG is True and supports CSP nonces. Requires loading the function into the Jinja environment.
```python
from jinja2 import Environment
from django_htmx.jinja import django_htmx_script, htmx_script
def environment(**options):
env = Environment(**options)
env.globals.update(
{
# ...
"django_htmx_script": django_htmx_script,
}
)
return env
```
```jinja
{% load django_htmx %}
...
```
--------------------------------
### Render Django HTMX Extension Script in Jinja Templates
Source: https://django-htmx.readthedocs.io/en/latest/template_tags.html
Renders only the django-htmx extension script when DEBUG is True in Jinja environments. Use this when you are sourcing htmx from an external file. Supports CSP nonces.
```python
from jinja2 import Environment
from django_htmx.jinja import django_htmx_script, htmx_script
def environment(**options):
env = Environment(**options)
env.globals.update({
# ...
"django_htmx_script": django_htmx_script,
})
return env
```
```jinja
{{ django_htmx_script() }}
```
```jinja
{{ django_htmx_script(nonce=csp_nonce) }}
```
--------------------------------
### Render HTMX Script Tag in Django Templates
Source: https://django-htmx.readthedocs.io/en/latest/template_tags.html
Renders both the vendored htmx script and the django-htmx extension script (if DEBUG is True). Supports minification control and CSP nonces on Django 6.0+.
```django
{% load django_htmx %}
...
{% htmx_script %}
...
```
```django
{% htmx_script minified=False %}
```
--------------------------------
### Render HTMX and Extension Scripts in Django Templates
Source: https://django-htmx.readthedocs.io/en/latest/_sources/template_tags.rst.txt
Renders both the vendored HTMX script and the django-htmx extension script for debugging in Django templates. The extension script is only included when settings.DEBUG is True. It supports minified and non-minified HTMX versions and CSP nonces on Django 6.0+.
```django
{% load django_htmx %}
...
{% htmx_script %}
...
```
```django
{% load django_htmx %}
...
{% htmx_script minified=False %}
...
```
--------------------------------
### Django HTMX HttpResponseLocation
Source: https://django-htmx.readthedocs.io/en/latest/http.html
The HttpResponseLocation class is used to instruct the client to navigate to a new URL. It's similar to HttpResponseClientRedirect but offers more control over the navigation behavior.
```python
from htmx_django.responses import HttpResponseLocation
def my_view(request):
return HttpResponseLocation('/another-url/', target='#main-content')
```
--------------------------------
### Replace URL with HTMX
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Uses replace_url to replace the current browser location history entry via the HX-Replace-Url header.
```python
from django_htmx.http import replace_url
def dashboard(request):
...
response = render(request, "dashboard.html", ...)
return replace_url(response, "/dashboard/")
```
--------------------------------
### trigger_client_event
Source: https://django-htmx.readthedocs.io/en/latest/http.html
Modifies HX-Trigger headers to trigger client-side events via HTMX.
```APIDOC
## trigger_client_event
### Description
Modify one of the `HX-Trigger` headers of `response` and return it. These headers make htmx trigger client-side events. Calling `trigger_client_event` multiple times for the same `response` and `after` will update the appropriate header, preserving existing event specifications.
### Method
N/A (Function within Django)
### Endpoint
N/A (Function within Django)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```python
from django.shortcuts import render
from django_htmx.http import trigger_client_event
def end_of_long_process(request):
response = render(request, "end-of-long-process.html")
return trigger_client_event(
response,
```
### Response
#### Success Response (200)
HttpResponse with `HX-Trigger` or related headers set.
#### Response Example
N/A (Function modifies an existing HttpResponse)
```
--------------------------------
### HTMX Response Header Helpers
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/http.html
Utility functions to modify existing HttpResponse objects by adding or updating HTMX-specific headers. These functions allow for dynamic control over URL pushing, swapping, targeting, and client-side event triggering.
```python
def push_url(response: _HttpResponse, url: str | Literal[False]) -> _HttpResponse:
response["HX-Push-Url"] = "false" if url is False else url
return response
def trigger_client_event(response: _HttpResponse, name: str, params: dict[str, Any] | None = None, *, after: Literal["receive", "settle", "swap"] = "receive") -> _HttpResponse:
# Implementation logic for setting HX-Trigger headers
header = f"HX-Trigger{'-After-Settle' if after == 'settle' else '-After-Swap' if after == 'swap' else ''}"
response[header] = json.dumps({name: params or {}})
return response
```
--------------------------------
### push_url Utility
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/http.html
Utility function to modify the browser's URL without reloading the page.
```APIDOC
## push_url
### Description
This function adds or modifies the browser's URL in the history stack using the `HX-Push-Url` header. It allows for updating the URL without causing a full page navigation.
### Method
N/A (Function definition)
### Endpoint
N/A
### Parameters
- **response** (_HttpResponse) - Required - The Django HTTP response object to modify.
- **url** (str | Literal[False]) - Required - The URL to push to the history, or `False` to disable.
### Request Example
N/A
### Response
#### Success Response (200)
- **Headers**: Includes `HX-Push-Url` with the specified URL or `false`.
#### Response Example
```python
from django.http import HttpResponse
from django_htmx.http import push_url
response = HttpResponse()
push_url(response, "/new/history/url")
# response will have HX-Push-Url: /new/history/url header
push_url(response, False)
# response will have HX-Push-Url: false header
```
```
--------------------------------
### HttpResponseStopPolling
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/http.html
Custom HttpResponse class to signal HTMX to stop polling.
```APIDOC
## HttpResponseStopPolling
### Description
This class extends Django's `HttpResponse` to set a custom status code (286) and reason phrase, indicating to HTMX that it should stop polling the server.
### Method
N/A (Class definition)
### Endpoint
N/A
### Parameters
None
### Request Example
N/A
### Response
#### Success Response (286)
- **Status Code**: 286
- **Reason Phrase**: "Stop Polling"
#### Response Example
```http
HTTP/1.1 286 Stop Polling
Content-Length: 0
```
```
--------------------------------
### Access HTMX Request Details
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/middleware.html
The HtmxDetails class provides a convenient interface to parse and access HTMX-specific request headers. It uses cached properties to efficiently retrieve values like current URL, target, and trigger events.
```python
class HtmxDetails:
def __init__(self, request):
self.request = request
def _get_header_value(self, name):
value = self.request.headers.get(name) or None
if value and self.request.headers.get(f"{name}-URI-AutoEncoded") == "true":
value = unquote(value)
return value
@cached_property
def target(self):
return self._get_header_value("HX-Target")
@cached_property
def trigger(self):
return self._get_header_value("HX-Trigger")
```
--------------------------------
### Django HTMX reswap() Function
Source: https://django-htmx.readthedocs.io/en/latest/http.html
The reswap() function allows you to specify how HTMX should swap the content on the page. You can choose from various swap strategies like 'innerHTML', 'outerHTML', 'beforebegin', etc.
```python
from htmx_django.functions import reswap
def my_view(request):
return reswap('outerHTML')
```
--------------------------------
### Django HTMX HttpResponseClientRedirect
Source: https://django-htmx.readthedocs.io/en/latest/http.html
The HttpResponseClientRedirect class is used to trigger a client-side redirect. It takes a URL as an argument and sets the appropriate headers for HTMX to perform the redirect.
```python
from htmx_django.responses import HttpResponseClientRedirect
def my_view(request):
return HttpResponseClientRedirect('/new-url/')
```
--------------------------------
### HttpResponseClientRefresh
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/http.html
Custom HttpResponse class to trigger a client-side page refresh via HTMX.
```APIDOC
## HttpResponseClientRefresh
### Description
This class generates an HTTP response that includes the `HX-Refresh` header set to `true`, instructing HTMX to perform a full page refresh.
### Method
N/A (Class definition)
### Endpoint
N/A
### Parameters
None
### Request Example
N/A
### Response
#### Success Response (200)
- **Headers**: Includes `HX-Refresh: true`.
#### Response Example
```http
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
HX-Refresh: true
Content-Length: 0
```
```
--------------------------------
### Django HTMX push_url Function for History Management
Source: https://django-htmx.readthedocs.io/en/latest/_sources/http.rst.txt
The push_url function is a utility that modifies a Django HTTP response to include the HX-Push-Url header. This header instructs HTMX to push a specified URL into the browser's location history, enabling proper back/forward navigation and bookmarking for dynamically updated content.
```python
from django_htmx.http import push_url
# Assuming 'response' is an existing Django HttpResponse object
response = push_url(response, "/new/url/")
```
--------------------------------
### HTMX Response Classes
Source: https://django-htmx.readthedocs.io/en/latest/_modules/django_htmx/http.html
Custom HttpResponse subclasses that set specific HTMX headers for client-side behavior. These classes handle scenarios like stopping polling, triggering redirects, refreshing the page, or specifying complex location redirects.
```python
class HttpResponseStopPolling(HttpResponse):
status_code = HTMX_STOP_POLLING
class HttpResponseClientRedirect(HttpResponseRedirectBase):
def __init__(self, redirect_to: str, *args: Any, **kwargs: Any) -> None:
super().__init__(redirect_to, *args, **kwargs)
self["HX-Redirect"] = self["Location"]
del self["Location"]
class HttpResponseClientRefresh(HttpResponse):
def __init__(self) -> None:
super().__init__()
self["HX-Refresh"] = "true"
```
--------------------------------
### HtmxDetails Attributes
Source: https://django-htmx.readthedocs.io/en/latest/genindex.html
Provides access to details about HTMX requests within Django views.
```APIDOC
## HtmxDetails Attributes
### Description
Access various attributes related to HTMX requests through the `HtmxDetails` object.
### Attributes
- **boosted** (bool) - Indicates if the request was boosted by HTMX.
- **current_url** (str) - The current URL of the request.
- **current_url_abs_path** (str) - The absolute path of the current URL.
- **history_restore_request** (bool) - Indicates if the request is a history restore.
- **prompt** (str) - The prompt value from the HTMX request.
- **target** (str) - The target element specified in the HTMX request.
- **trigger** (str) - The trigger element specified in the HTMX request.
- **trigger_name** (str) - The name of the trigger element.
- **triggering_event** (str) - The event that triggered the HTMX request.
```
--------------------------------
### Trigger Client Events with Django HTMX
Source: https://django-htmx.readthedocs.io/en/latest/_sources/http.rst.txt
The `trigger_client_event` function modifies HTMX trigger headers (`HX-Trigger`, `HX-Trigger-After-Settle`, `HX-Trigger-After-Swap`) to make HTMX fire custom client-side events. It allows specifying the event name, optional parameters, and when the event should be triggered relative to the HTMX swap.
```python
from django.shortcuts import render
from django_htmx.http import trigger_client_event
# Example usage within a Django view:
def my_view(request):
...
response = render(request, 'my_template.html', context)
# Trigger a 'custom-event' after the swap
trigger_client_event(response, 'custom-event', {'data': 'some value'}, after='swap')
return response
```
--------------------------------
### HTMX Constants
Source: https://django-htmx.readthedocs.io/en/latest/genindex.html
Defines constants used within the django-htmx library.
```APIDOC
## HTMX Constants
### Description
Provides constants used throughout the django-htmx library, particularly for controlling polling behavior.
### Constant
- **HTMX_STOP_POLLING** (in module django_htmx.http) - A constant used to signal the stopping of HTMX polling.
```
--------------------------------
### Django HTMX reselect() Function
Source: https://django-htmx.readthedocs.io/en/latest/http.html
The reselect() function allows you to specify a CSS selector for the content within the response that should be used for swapping. This is useful when the response contains more than just the content to be swapped.
```python
from htmx_django.functions import reselect
def my_view(request):
return reselect('.content-to-update')
```
--------------------------------
### HTMX Utility Functions
Source: https://django-htmx.readthedocs.io/en/latest/genindex.html
Functions for manipulating HTMX-related HTTP headers and responses.
```APIDOC
## HTMX Utility Functions
### Description
Provides utility functions for common HTMX operations, including URL manipulation and event triggering.
### Functions
- **push_url**(url: str) - Pushes a new URL onto the browser's history.
- **replace_url**(url: str) - Replaces the current URL in the browser's history.
- **reselect**(selector: str) - Reselects elements on the page.
- **reswap**(swap_style: str) - Changes the swap style for HTMX updates.
- **retarget**(selector: str) - Changes the target for HTMX updates.
- **trigger_client_event**(event_name: str, details: dict = None) - Triggers a custom event on the client side.
```
--------------------------------
### Django Base HTML Template with HTMX
Source: https://django-htmx.readthedocs.io/en/latest/_sources/tips.rst.txt
This Django template defines the main site structure, including the head and body sections, and a placeholder for the main content block. It's designed to be extended by other templates.
```django
{% extends base_template %}
{% block main %}
...
{% endblock %}
```