### Loading and disabling example with request keys Source: https://hyperdjango.charingcrosscapital.com/docs/declarative-html-apis This example combines several loading and disabling attributes to manage the UI during a search operation. It shows a search input, a search button, a delayed loading indicator scoped by key, and a disable button to prevent double submissions. ```html

Searching...

``` -------------------------------- ### Install HyperDjango Source: https://hyperdjango.charingcrosscapital.com/docs/getting-started Install the HyperDjango package using pip. Ensure your Python and Django versions meet the requirements. ```bash pip install hyperdjango ``` -------------------------------- ### Scaffold Starter Project Source: https://hyperdjango.charingcrosscapital.com/docs/getting-started Use the `hyper_scaffold` management command to quickly generate a basic HyperDjango project structure, including Vite configuration and example files. ```bash python manage.py hyper_scaffold ``` -------------------------------- ### Return Multiple Action Items Immediately Source: https://hyperdjango.charingcrosscapital.com/docs/actions When the entire response is known immediately, return a list of action items. This example creates a new list item and shows a success toast. ```python from __future__ import annotations from hyperdjango.actions import HTML, Toast, action from hyperdjango.page import HyperView class PageView(HyperView): @action def create(self, request): return [ HTML(content="
  • New item
  • ", target="#todo-list", swap="append"), Toast(payload={"type": "success", "message": "Created"}), ] ``` -------------------------------- ### HyperView with get_context() Source: https://hyperdjango.charingcrosscapital.com/docs/pages-and-rendering Extend get_context() to provide common values for every request on a page. This example adds a site name to the context. ```python from __future__ import annotations from django.http import HttpRequest from hyperdjango.page import HyperView class PageView(HyperView): def get_context(self, request: HttpRequest) -> dict[str, object]: context = super().get_context(request) context["site_name"] = "HyperDjango Demo" return context def get(self, request: HttpRequest) -> dict[str, str]: return {"title": "Dashboard"} ``` -------------------------------- ### Patch HTML Content with Options Source: https://hyperdjango.charingcrosscapital.com/docs/actions Use `HTML(...)` to patch specific HTML content into a target element on the page. This example demonstrates advanced options like `swap` and `transition`. ```python from __future__ import annotations from hyperdjango.actions import HTML, action from hyperdjango.page import HyperView class PageView(HyperView): @action def save(self, request): return [ HTML( content="
    Saved
    ", target="#flash", swap="outer", transition=True, focus="preserve", ) ] ``` -------------------------------- ### Create First HyperDjango Page Source: https://hyperdjango.charingcrosscapital.com/docs/getting-started Define a basic page view using `HyperView` in `hyper/routes/about/+page.py`. This view handles GET requests and returns page data. ```python from __future__ import annotations from django.http import HttpRequest from hyperdjango.page import HyperView class PageView(HyperView): def get(self, request: HttpRequest) -> dict[str, str]: return {"title": "About"} ``` -------------------------------- ### Passing Data to Actions Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions The data object is sent to the server and merged into action kwargs. This example shows passing a query and a page number. ```html ``` -------------------------------- ### HyperView render() for Partials Source: https://hyperdjango.charingcrosscapital.com/docs/pages-and-rendering Use render() to render templates relative to the current page or template class, ideal for page-local partials. This example renders a preview partial. ```python from __future__ import annotations from django.http import HttpRequest from hyperdjango.page import HyperView class PageView(HyperView): def preview(self, request: HttpRequest) -> str: return self.render( request=request, relative_template_name="partials/preview.html", context_updates={"message": "Hello"}, ) ``` -------------------------------- ### Create a Page View Inheriting from BaseLayout Source: https://hyperdjango.charingcrosscapital.com/docs/layouts Define a page view that inherits from your custom BaseLayout. Implement HTTP methods like 'get' to return data for the page. ```python from __future__ import annotations from django.http import HttpRequest from hyper.layouts.base import BaseLayout class PageView(BaseLayout): def get(self, request: HttpRequest) -> dict[str, str]: return {"title": "About", "content": "This page inherits BaseLayout."} ``` -------------------------------- ### render_template_page() for Standalone Templates Source: https://hyperdjango.charingcrosscapital.com/docs/pages-and-rendering Render a standalone template class as a normal Django response using render_template_page(). This example renders a ProfileCardTemplate. ```python from __future__ import annotations from django.http import HttpRequest, HttpResponse from hyper.templates.profile_card.page import ProfileCardTemplate from hyperdjango.shortcuts import render_template_page def profile_card(request: HttpRequest) -> HttpResponse: return render_template_page( request, ProfileCardTemplate, context={"name": "Waseem", "role": "Engineer"}, ) ``` -------------------------------- ### HyperView render_block() for Specific Blocks Source: https://hyperdjango.charingcrosscapital.com/docs/pages-and-rendering Use render_block() to render a single named block from a template. This example renders a 'todo_list' block with provided items. ```python from __future__ import annotations from django.http import HttpRequest from hyperdjango.page import HyperView class PageView(HyperView): def todo_list_html(self, request: HttpRequest) -> str: return self.render_block( request=request, block_name="todo_list", context_updates={"items": ["Write docs", "Ship feature"]}, ) ``` -------------------------------- ### Plain Django View for Routing Source: https://hyperdjango.charingcrosscapital.com/docs/pages-and-rendering Use a plain Django View subclass when only file-based routing is needed, without other HyperDjango features. This example shows basic routing for a slug. ```python from __future__ import annotations from django.http import HttpRequest, HttpResponse from django.views import View class PageView(View): def get(self, request: HttpRequest, slug: str) -> HttpResponse: return HttpResponse(f"Post: {slug}") ``` -------------------------------- ### Stream Action Items Over Time Source: https://hyperdjango.charingcrosscapital.com/docs/actions Use a generator to stream action items over time, suitable for long-running jobs. This example updates a job status message and concludes with a toast and redirect. ```python from __future__ import annotations from time import sleep from hyperdjango.actions import HTML, Redirect, Toast, action from hyperdjango.page import HyperView class PageView(HyperView): @action def run_job(self, request): yield HTML(content="

    Starting...

    ", target="#job-status") sleep(1) yield HTML(content="

    Working...

    ", target="#job-status") sleep(1) yield Toast(payload={"type": "success", "message": "Done"}) yield Redirect(url="/done/") ``` -------------------------------- ### Server-Side Action Definition Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Define server-side actions using the @action decorator on a method within a HyperView class. This example defines a 'search' action. ```python from __future__ import annotations from hyperdjango.actions import action from hyperdjango.page import HyperView class PageView(HyperView): @action def search(self, request, q: str = "", page: int = 1): ... ``` -------------------------------- ### Define a Basic HyperDjango Action Source: https://hyperdjango.charingcrosscapital.com/docs/actions Use the `@action` decorator to define an action method within a HyperView class. This example shows a simple save action returning an HTML patch. ```python from __future__ import annotations from hyperdjango.actions import HTML, action from hyperdjango.page import HyperView class PageView(HyperView): @action def save(self, request): return [HTML(content="
    Saved
    ", target="#flash")] ``` -------------------------------- ### Configure Core Settings for Assets and Vite Source: https://hyperdjango.charingcrosscapital.com/docs/assets-and-vite Set up directories for frontend assets and Vite output, specify the Vite development server URL, and control development mode asset loading. Ensure template directories and static file directories are correctly configured. ```python HYPER_FRONTEND_DIR = BASE_DIR / "hyper" HYPER_VITE_OUTPUT_DIR = BASE_DIR / "dist" HYPER_VITE_DEV_SERVER_URL = "http://localhost:5173/" HYPER_DEV = DEBUG TEMPLATES[0]["DIRS"].append(HYPER_FRONTEND_DIR) STATICFILES_DIRS = [HYPER_VITE_OUTPUT_DIR] ``` -------------------------------- ### Import Rendering Shortcuts Source: https://hyperdjango.charingcrosscapital.com/docs/reference/pages-and-rendering Import common rendering shortcuts: render_template_block and render_template_page from hyperdjango.shortcuts. ```python from hyperdjango.shortcuts import render_template_block, render_template_page ``` -------------------------------- ### Overriding HTTP Method Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use the 'method' option to specify a different HTTP method (e.g., GET) than the default POST for actions. ```html ``` -------------------------------- ### Initialize Alpine.js and Import Styles Source: https://hyperdjango.charingcrosscapital.com/docs/layouts Set up Alpine.js for frontend interactivity and import necessary CSS for the layout. This file is typically located in the layout's root directory. ```typescript import Alpine from "alpinejs"; import "./base.css"; Alpine.start(); ``` -------------------------------- ### Including Runtime Scripts Source: https://hyperdjango.charingcrosscapital.com/docs/base-template Include the core HyperDjango runtime script and the Alpine bridge script. Omit Alpine if not needed. ```html ``` -------------------------------- ### Generate Project Structure with hyper_scaffold Source: https://hyperdjango.charingcrosscapital.com/docs/reference/commands Use `hyper_scaffold` to generate a starter HyperDjango project structure. Flags like `--no-wire` prevent automatic patching of Django settings and URLs, while `--force` overwrites existing files. ```bash python manage.py hyper_scaffold ``` ```bash python manage.py hyper_scaffold --no-wire ``` ```bash python manage.py hyper_scaffold --force ``` -------------------------------- ### Combining Local and Global Signals in Alpine.js Source: https://hyperdjango.charingcrosscapital.com/docs/alpine-integration Demonstrates how to simultaneously update both local x-data and global $store.hyper using a single HyperDjango action that returns multiple Signals. ```python from __future__ import annotations from hyperdjango.actions import action from hyperdjango.integrations.alpine.actions import Signals from hyperdjango.page import HyperView class PageView(HyperView): @action def increment_both(self, request, current: int = 0): local_count = int(current) + 1 global_count = 42 return [Signals(values={"count": local_count, "$count": global_count})] ``` ```html

    Local:

    Global:

    ``` -------------------------------- ### `window.action(name, data, options)` Source: https://hyperdjango.charingcrosscapital.com/docs/reference/client-runtime The plain JavaScript equivalent of `$action(...)`. It provides the same functionality for triggering server-side actions. ```APIDOC ## `window.action(name, data, options)` ### Description Plain JavaScript equivalent of `$action(...)`. Arguments are the same as `$action(...)`. ### Arguments * `name` (str): Action name to call on the server. * `data` (dict[str, Any]): Data merged into the action kwargs. * `options` (dict[str, Any]): Client-side request options. ``` -------------------------------- ### Triggering Actions with Vanilla JavaScript Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use the global window.action function for plain JavaScript. This is useful when not using a framework like Alpine.js. ```html ``` -------------------------------- ### Verify HyperDjango Routes Source: https://hyperdjango.charingcrosscapital.com/docs/getting-started Use the `hyper_routes` management command to inspect and verify your project's configured routes. The `--json` flag provides output in a machine-readable format. ```bash python manage.py hyper_routes python manage.py hyper_routes --json ``` -------------------------------- ### Configure HYPER_FRONTEND_DIR Source: https://hyperdjango.charingcrosscapital.com/docs/reference/settings Set the path to your 'hyper/' directory, which typically contains routes, layouts, templates, and shared frontend files. This tells HyperDjango where to find your frontend code. ```python HYPER_FRONTEND_DIR = BASE_DIR / "hyper" ``` -------------------------------- ### Build Server-Driven UI Responses Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Construct a list of response items, such as HTML updates and history manipulations, using HyperDjango's action utilities. ```python from __future__ import annotations from hyperdjango.actions import HTML, History def build_result(results_html: str, q: str): return [ HTML( content=results_html, target="#results", swap="inner", transition=True, focus="preserve", ), History(replace_url=f"/search/?q={q}"), ] ``` -------------------------------- ### Loading Template Tags Source: https://hyperdjango.charingcrosscapital.com/docs/base-template Ensure you load the necessary static and hyper tags when using or replacing the base template. ```html {% load static hyper_tags %} ``` -------------------------------- ### Enable browser view transitions with server response Source: https://hyperdjango.charingcrosscapital.com/docs/declarative-html-apis This Python code demonstrates how to return an HTML response that enables view transitions for a specific DOM element. The `transition=True` argument and the `target` selector are crucial for this functionality. ```python from __future__ import annotations from hyperdjango.actions import HTML, action from hyperdjango.page import HyperView class PageView(HyperView): @action def update_profile(self, request): return [ HTML( content="
    Updated
    ", target="#profile-panel", transition=True, ) ] ``` -------------------------------- ### Request Coordination with Keys Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use 'key' to group requests into named coordination lanes. This affects sync behavior, loading indicators, and disable states. ```html

    Searching...

    ``` -------------------------------- ### Import include_routes Source: https://hyperdjango.charingcrosscapital.com/docs/reference/django-integration Import the `include_routes` function from `hyperdjango.urls`. ```python from hyperdjango.urls import include_routes ``` -------------------------------- ### Return a String Response Source: https://hyperdjango.charingcrosscapital.com/docs/actions A simple string can be returned, which the runtime will typically interpret as an HTML response to be placed in a default target. ```python from __future__ import annotations from hyperdjango.actions import action from hyperdjango.page import HyperView class PageView(HyperView): @action def simple(self, request): return "
    Saved
    " ``` -------------------------------- ### Configure HYPER_VITE_OUTPUT_DIR Source: https://hyperdjango.charingcrosscapital.com/docs/reference/settings Specify the directory where Vite writes its built assets. This is used by HyperDjango to locate production-ready frontend files. ```python HYPER_VITE_OUTPUT_DIR = BASE_DIR / "dist" ``` -------------------------------- ### First Page HTML Template Source: https://hyperdjango.charingcrosscapital.com/docs/getting-started Create an HTML template for your page in `hyper/routes/about/index.html`. This template uses Django template syntax to display data from the view. ```html

    {{ title }}

    This page was rendered by HyperDjango.

    ``` -------------------------------- ### Configure HYPER_VITE_DEV_SERVER_URL Source: https://hyperdjango.charingcrosscapital.com/docs/reference/settings Set the URL for the Vite development server. HyperDjango injects this URL during development to serve assets directly from the dev server. ```python HYPER_VITE_DEV_SERVER_URL = "http://localhost:5173/" ``` -------------------------------- ### Define a Base Layout Class in Python Source: https://hyperdjango.charingcrosscapital.com/docs/layouts Inherit from HyperView to create a base layout. Override get_context to provide shared data to all templates using this layout. ```python from __future__ import annotations from typing import Any from django.http import HttpRequest from hyperdjango.page import HyperView class BaseLayout(HyperView): def get_context(self, request: HttpRequest) -> dict[str, Any]: context = super().get_context(request) context["site_name"] = "HyperDjango Example" return context ``` -------------------------------- ### Browser Redirect Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions Use `Redirect` to immediately redirect the browser to a new URL. If returned from a list or generator, it acts as the final item. ```python from hyperdjango.actions import Redirect # Example usage: Redirect(url='/new-page') ``` -------------------------------- ### Action Loading Attributes Source: https://hyperdjango.charingcrosscapital.com/docs/reference/client-runtime These options define how the client runtime orchestrates the request lifecycle, state, and coordination for actions. ```APIDOC ## Action Loading Attributes These options define how the client runtime orchestrates request lifecycle, state, and coordination. ### `form` * **Type**: `CSS selector string | HTMLFormElement` * **Purpose**: Associates the action with an existing form. * **Behavior**: * Extracts method and URL from the form element. * Automatically serializes form fields into the action kwargs. * Form fields are overridden by explicit JSON action data if keys collide. ### `method` * **Type**: `str` (e.g., `"GET"`, `"POST"`) * **Purpose**: Explicitly overrides the request method. * **Default**: Derived from the associated `form` if present, otherwise `"POST"` for actions. ### `url` * **Type**: `str` * **Purpose**: Defines the target URL for the action request. * **Default**: The current browser URL. ### `sync` * **Type**: `"replace" | "block" | "none"` * **Purpose**: Defines how concurrent requests in the same coordination lane are handled. * **Options**: * `replace`: Cancels the existing in-flight request and sends the new one. * `block`: Ignores the new request while an existing one is still in-flight. * `none`: Allows multiple concurrent requests to proceed. * **Defaults**: * `block` for form-backed requests. * `replace` for non-form requests. ### `key` * **Type**: `str` * **Purpose**: Identifies the specific coordination lane for `sync` behavior. * **Behavior**: * Requests with the same key share the same `sync` policy and loading state. * If omitted, the runtime automatically derives a key based on the action name and target. ### `onBeforeSubmit` * **Type**: `(requestOptions) => void | boolean` * **Purpose**: Client-side hook immediately before the request is dispatched. * **Behavior**: If it returns `false`, the request is aborted. Useful for client-side validation. ### `onUploadProgress` * **Type**: `(progressEvent) => void` * **Purpose**: Enables tracking for multipart/form-data upload progress. * **Behavior**: Provides access to `loaded` and `total` bytes for UI progress indicators. ``` -------------------------------- ### Basic PageView Structure Source: https://hyperdjango.charingcrosscapital.com/docs/routing Defines a basic PageView class for a route. Requires importing HttpRequest and HyperView. ```python from __future__ import annotations from django.http import HttpRequest from hyperdjango.page import HyperView class PageView(HyperView): def get(self, request: HttpRequest) -> dict[str, str]: return {"title": "About"} ``` -------------------------------- ### Handle Action Success Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use the .then() method to execute code when an action successfully completes. ```html ``` -------------------------------- ### Patching Global Signals into $store.hyper with Alpine.js Source: https://hyperdjango.charingcrosscapital.com/docs/alpine-integration Define a Python action that returns a Signal with a '$' prefix to patch a value into Alpine.js's global $store.hyper object. This is useful for managing global application state. ```python from __future__ import annotations from hyperdjango.actions import action from hyperdjango.integrations.alpine.actions import Signal from hyperdjango.page import HyperView class PageView(HyperView): @action def reset_global(self, request): return [Signal(name="$count", value=0)] ``` ```html
    ``` -------------------------------- ### Catch-All Parameter Route Source: https://hyperdjango.charingcrosscapital.com/docs/routing Matches any remaining path segments. The entire matched path is passed as a single string, which can be split into parts. ```python from __future__ import annotations from django.http import HttpRequest from hyperdjango.page import HyperView class PageView(HyperView): def get(self, request: HttpRequest, path: str) -> dict[str, object]: parts = [part for part in path.split("/") if part] return {"raw_path": path, "parts": parts} ``` -------------------------------- ### HyperView render_template() for Self-Contained Templates Source: https://hyperdjango.charingcrosscapital.com/docs/pages-and-rendering Use render_template() to render a directory containing an index.html and optional entry script. This is for action-time HTML and JS insertion. ```python from __future__ import annotations from django.http import HttpRequest from hyperdjango.page import HyperView class PageView(HyperView): def modal_partial(self, request: HttpRequest): return self.render_template( "partials/confirm_modal", request=request, context_updates={"title": "Confirm", "message": "Continue?"}, ) ``` -------------------------------- ### Redirecting to a New URL with Redirect Source: https://hyperdjango.charingcrosscapital.com/docs/actions Use `Redirect(...)` when the interaction should navigate the user to a different URL, effectively leaving the current page. ```python from __future__ import annotations from hyperdjango.actions import Redirect, action from hyperdjango.page import HyperView class PageView(HyperView): @action def finish(self, request): return [Redirect(url="/dashboard/")] ``` -------------------------------- ### Return Multiple Actions Using Actions Container Source: https://hyperdjango.charingcrosscapital.com/docs/actions The `Actions(...)` container can be used to group multiple action items, similar to returning a list. This is an alternative syntax for returning multiple items. ```python from __future__ import annotations from hyperdjango.actions import Actions, HTML, Toast, action from hyperdjango.page import HyperView class PageView(HyperView): @action def create(self, request): return Actions( HTML(content="
  • New item
  • ", target="#todo-list", swap="append"), Toast(payload={"type": "success", "message": "Created"}), ) ``` -------------------------------- ### Specifying Action URL Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use the 'url' option to direct the action to a different URL than the current page. ```html ``` -------------------------------- ### render_template_page shortcut Source: https://hyperdjango.charingcrosscapital.com/docs/reference/pages-and-rendering Shortcut function for rendering a template page. ```APIDOC ## render_template_page ### Import ```python from hyperdjango.shortcuts import render_template_page ``` ``` -------------------------------- ### Return a Dictionary for Template Context Source: https://hyperdjango.charingcrosscapital.com/docs/actions Returning a dictionary allows the action to provide context data for rendering a block within the current page's template. The dictionary keys become template variables. ```python from __future__ import annotations from hyperdjango.actions import action from hyperdjango.page import HyperView class PageView(HyperView): @action def stats(self, request): return {"count": 12, "completed": 4} ``` ```html {% block stats %}
    {{ count }} total, {{ completed }} completed
    {% endblock stats %} ``` -------------------------------- ### Configure HYPER_DEV for Asset Loading Source: https://hyperdjango.charingcrosscapital.com/docs/reference/settings Control asset loading behavior between development and production modes. When True, it uses Vite dev server URLs and injects '@vite/client'. When False, it resolves assets from the Vite manifest. ```python HYPER_DEV = DEBUG ``` -------------------------------- ### Mount HyperDjango Routes with Prefix Source: https://hyperdjango.charingcrosscapital.com/docs/getting-started Optionally, mount HyperDjango routes under a specific URL prefix by providing the `url_prefix` argument to `include_routes()`. ```python urlpatterns = [ *include_routes(url_prefix="app"), ] ``` -------------------------------- ### Import HyperPageTemplate Source: https://hyperdjango.charingcrosscapital.com/docs/reference/pages-and-rendering Import the HyperPageTemplate class from hyperdjango.page. Use this for standalone renderable template classes outside of routed pages. ```python from hyperdjango.page import HyperPageTemplate ``` -------------------------------- ### Controlling Request Synchronization (sync: 'none') Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use 'sync: 'none'' to allow multiple concurrent requests without coordination. Suitable for actions that can be triggered rapidly and independently. ```html ``` -------------------------------- ### Triggering Actions with Alpine.js Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use the Alpine.js $action helper to invoke server-side actions. Pass the action name, data, and options like key for coordination. ```html
    ``` -------------------------------- ### Patching Local Signals into x-data with Alpine.js Source: https://hyperdjango.charingcrosscapital.com/docs/alpine-integration Define a Python action that returns a Signal to patch a value into the nearest Alpine.js x-data scope. This allows for concise local state management. ```python from __future__ import annotations from hyperdjango.actions import action from hyperdjango.integrations.alpine.actions import Signal from hyperdjango.page import HyperView class PageView(HyperView): @action def counter(self, request, count: int = 0): return [Signal(name="count", value=int(count) + 1)] ``` ```html
    ``` -------------------------------- ### Supported Return Shapes Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions Details the recommended and supported return shapes for actions, including lists, generators, single items, and various data types. ```APIDOC ## Return Shapes ### Recommended * list of action items * generator yielding action items ### Supported by the current runtime * single action item * `Actions(...)` * `str` * `dict` * `HttpResponse` ### Recommended guidance * use a list when the whole response is known immediately * use a generator when the response should stream over time * use typed action items for clarity ### Dispatch compatibility details * `str` is converted into a patch action * `dict` is treated as context for `render_block(...)` * `HttpResponse` is passed through after Hyper headers are ensured ``` -------------------------------- ### `Actions(*items)` Wrapper Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions The `Actions` class is a wrapper around multiple typed action items, making them iterable at runtime and functionally equivalent to returning a list of action items. ```APIDOC ## `Actions(*items)` Wrapper ### Purpose Wrapper around multiple typed action items. ### Arguments * `*items: ActionItem` ### Notes * Iterable at runtime * Functionally equivalent to returning a list of action items ``` -------------------------------- ### Listen for uploadProgress Event Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Monitor 'hyper:uploadProgress' events to track the progress of file uploads, filtering by a specific key. ```javascript window.addEventListener("hyper:uploadProgress", (event) => { if (event.detail.key !== "avatar-upload") { return; } console.log(event.detail.loaded, event.detail.total, event.detail.progress); }); ``` -------------------------------- ### Mount HyperDjango Routes Source: https://hyperdjango.charingcrosscapital.com/docs/getting-started Integrate HyperDjango's file-based routing into your Django project's URL patterns by including `include_routes()`. ```python from django.contrib import admin from django.urls import path from hyperdjango.urls import include_routes urlpatterns = [ path("admin/", admin.site.urls), *include_routes(), ] ``` -------------------------------- ### Runtime Events Source: https://hyperdjango.charingcrosscapital.com/docs/reference/client-runtime A list of events dispatched by the HyperDjango client runtime to `window` for lifecycle monitoring and integration. ```APIDOC ## Runtime Events The HyperDjango client runtime dispatches events to `window` for lifecycle monitoring and integration. Event | Fired When | Payload Properties ---|---|--- `hyper:beforeRequest` | Immediately before sending an action request. | `key`, `url`, `method`, `action` `hyper:afterRequest` | After a request completes or fails. | `key` `hyper:requestBlocked` | When `sync="block"` prevents a new request. | `key` `hyper:requestReplaced` | When `sync="replace"` aborts an in-flight request. | `key` `hyper:requestAborted` | When a request is intentionally cancelled. | `key` `hyper:requestSuccess` | When a request completes successfully. | `key`, `status` `hyper:requestError` | When the server returns an error status. | `key`, `status`, `message` `hyper:requestException` | When client-side code throws an exception. | `key`, `error` `hyper:uploadProgress` | During file upload progress tracking. | `key`, `progress` (0-1) `hyper:streamEvent` | When a new SSE event is received from the server. | `event` (type), `data` (payload) `hyper:toast` | When a `Toast` action is received. | `value` ``` -------------------------------- ### Handle Rejected Actions Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use the .catch() method to handle errors when an action fails or is rejected. ```html ``` -------------------------------- ### render_template_block shortcut Source: https://hyperdjango.charingcrosscapital.com/docs/reference/pages-and-rendering Shortcut function for rendering a specific template block. ```APIDOC ## render_template_block ### Import ```python from hyperdjango.shortcuts import render_template_block ``` ``` -------------------------------- ### Add HyperDjango to INSTALLED_APPS Source: https://hyperdjango.charingcrosscapital.com/docs/getting-started Include 'hyperdjango' in your Django project's INSTALLED_APPS setting to enable its features. ```python INSTALLED_APPS = [ # ... "hyperdjango", ] ``` -------------------------------- ### Configure HyperDjango Settings Source: https://hyperdjango.charingcrosscapital.com/docs/getting-started Configure essential HyperDjango settings in your Django settings file, including directories for frontend files, Vite output, and the development server URL. ```python HYPER_FRONTEND_DIR = BASE_DIR / "hyper" HYPER_VITE_OUTPUT_DIR = BASE_DIR / "dist" HYPER_VITE_DEV_SERVER_URL = "http://localhost:5173/" HYPER_DEV = DEBUG TEMPLATES[0]["DIRS"].append(HYPER_FRONTEND_DIR) STATICFILES_DIRS = [HYPER_VITE_OUTPUT_DIR] ``` -------------------------------- ### `$action(name, data, options)` Source: https://hyperdjango.charingcrosscapital.com/docs/reference/client-runtime Available in Alpine environments through the HyperDjango Alpine bridge. This function allows you to call server-side actions directly from your frontend JavaScript. ```APIDOC ## `$action(name, data, options)` ### Description Available in Alpine environments through the HyperDjango Alpine bridge. This function allows you to call server-side actions directly from your frontend JavaScript. ### Arguments * `name` (str): Action name to call on the server. * `data` (dict[str, Any]): Data merged into the action kwargs. * `options` (dict[str, Any]): Client-side request options. ### Request Metadata Request metadata sent by the runtime can include: * `X-Hyper-Action` * `X-Hyper-Target` * `X-Hyper-Data` * `X-Requested-With` ``` -------------------------------- ### Minimal HyperView Page Source: https://hyperdjango.charingcrosscapital.com/docs/pages-and-rendering A basic HyperView subclass for routed pages, combining Django view dispatch with template rendering and action dispatch. Use for standard routed pages. ```python from __future__ import annotations from django.http import HttpRequest from hyperdjango.page import HyperView class PageView(HyperView): def get(self, request: HttpRequest) -> dict[str, str]: return {"title": "Home"} ``` -------------------------------- ### HyperView.get_context Source: https://hyperdjango.charingcrosscapital.com/docs/reference/pages-and-rendering Builds the base template context for the page. Typically extended with `super().get_context(request)`. ```APIDOC ## get_context(request) ### Signature ```python def get_context(self, request: HttpRequest) -> dict[str, Any]: ... ``` ### Purpose - build the base template context for the page - usually extended with `super().get_context(request)` ``` -------------------------------- ### `HTML(...)` Action Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions Used to patch HTML content into the page with various DOM insertion modes and transition options. ```APIDOC ## `HTML(...)` Action ### Arguments * `content: str | None = None` - HTML string to patch into the page * `target: str | None = None` - CSS selector the client runtime should patch * `swap: str = "outer"` - DOM insertion mode. Supported values: `inner`, `outer`, `before`, `after`, `prepend`, `append`, `delete`, `none`. * `transition: bool = False` - Whether to request view-transition-aware patching * `focus: str | None = None` - Focus mode after patching. Common values are handled by the client runtime such as preserving focus or moving to the first invalid field. * `swap_delay: int | None = None` - Delay before the swap step starts * `settle_delay: int | None = None` - Delay before the settle step completes * `strict_targets: bool | None = None` - Whether missing targets should fail loudly for this patch ### Event emitted to the client runtime * `patch_html` ``` -------------------------------- ### Minimal Custom Base Template Source: https://hyperdjango.charingcrosscapital.com/docs/base-template A minimal custom base template that includes essential HyperDjango components like asset tags, runtime scripts, and CSRF handling. ```html {% load static hyper_tags %} {{ title|default:"My App" }} {% hyper_preloads %} {% hyper_stylesheets %} {% hyper_head_scripts %} {% block body %}{% endblock body %} {% hyper_body_scripts %} ``` -------------------------------- ### `Redirect(url, replace=False)` Action Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions Performs an immediate browser redirect to a specified URL, optionally replacing the current history entry. ```APIDOC ## `Redirect(url, replace=False)` Action ### Arguments * `url: str` * `replace: bool = False` ### Behavior * redirects the browser immediately * if returned from a list or generator, treat it as the last item because later items are not delivered ### Event emitted to the client runtime * `redirect` ``` -------------------------------- ### Import HyperView Source: https://hyperdjango.charingcrosscapital.com/docs/reference/pages-and-rendering Import the HyperView class from hyperdjango.page. This class is used for routed pages and provides template rendering and action registration APIs. ```python from hyperdjango.page import HyperView ``` -------------------------------- ### Server-Side Action Detection Source: https://hyperdjango.charingcrosscapital.com/docs/reference/client-runtime Details on how the server detects and processes action requests based on request headers and parameters. ```APIDOC ## Server-Side Action Detection At dispatch time, the server treats a request as an action request when an action name is present through one of these sources: * `X-Hyper-Action` * query string `_action` * POST field `_action` Action kwargs are assembled in this order: 1. JSON from `X-Hyper-Data` 2. query parameters not already present 3. POST fields not already present for non-GET requests ``` -------------------------------- ### HyperView.render_template Source: https://hyperdjango.charingcrosscapital.com/docs/reference/pages-and-rendering Renders a specific template directory, expecting an `index.html` within it. Returns a `HyperPartialTemplateResult` containing HTML and optional JS. ```APIDOC ## render_template(template_dir, request, context_updates=None) ### Signature ```python def render_template( self, template_dir: str, *, request: HttpRequest, context_updates: dict[str, Any] | None = None, ) -> HyperPartialTemplateResult: ... ``` ### Arguments - `template_dir` Directory relative to the current file location. HyperDjango expects `index.html` inside it. - `request` Current Django request - `context_updates` Extra context merged into the render ### Returns - `HyperPartialTemplateResult` ### Fields - `html: str` - `js: str | None` ### Limitation - action-time partial rendering only exposes HTML and one body JS entry path ``` -------------------------------- ### Display Toast Notification Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions Use `Toast` to emit a notification to the client, which your frontend can choose to display. The payload can be any data. ```python from hyperdjango.actions import Toast # Example usage: Toast(payload='Operation successful!') ``` -------------------------------- ### Render Custom Entry Scripts Source: https://hyperdjango.charingcrosscapital.com/docs/reference/template-tags Use `hyper_custom_entry` with a specific name to render scripts for `name.entry.js` or `name.entry.ts`. If neither exists, a `FileNotFoundError` is raised. The resolution order prioritizes `.js` over `.ts`. ```django {% hyper_custom_entry "admin" %} ``` -------------------------------- ### HyperView.render Source: https://hyperdjango.charingcrosscapital.com/docs/reference/pages-and-rendering Renders the page's HTML content. Allows specifying a relative template name and additional context updates. ```APIDOC ## render(request, relative_template_name="", context_updates=None) ### Signature ```python def render( self, *, request: HttpRequest, relative_template_name: str = "", context_updates: dict[str, Any] | None = None, ) -> str: ... ``` ### Arguments - `request` Current Django request - `relative_template_name` Template path relative to the current page or template class directory. If omitted, `index.html` is used. - `context_updates` Extra context merged on top of `get_context(request)`. ### Returns - rendered HTML string ``` -------------------------------- ### `Toast(payload)` Action Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions Emits a toast event to the client, allowing the frontend to display a message in a toast notification. ```APIDOC ## `Toast(payload)` Action ### Arguments * `payload: Any` ### Behavior * emitted to the client as `hyper:toast` * your frontend chooses how to display it ### Event emitted to the client runtime * `toast` ``` -------------------------------- ### Inspect Compiled Routes with hyper_routes Source: https://hyperdjango.charingcrosscapital.com/docs/reference/commands Use `hyper_routes` to print compiled routes for inspection. The `--json` flag outputs route metadata in JSON format, useful for CI to catch route conflicts early. You can also specify a `--prefix` or override the routes directory with `--dir`. ```bash python manage.py hyper_routes ``` ```bash python manage.py hyper_routes --json ``` ```bash python manage.py hyper_routes --prefix "/api/v1/" ``` ```bash python manage.py hyper_routes --dir "my_routes/" ``` -------------------------------- ### `LoadJS(src)` Action Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions Dynamically loads a JavaScript module script after the action response has reached the client. ```APIDOC ## `LoadJS(src)` Action ### Arguments * `src: str` ### Behavior * loads a module script dynamically after the action response reaches the client ### Event emitted to the client runtime * `load_js` ``` -------------------------------- ### Isolating Concurrent Work with Different Keys Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Assigning different keys to actions ensures they operate independently, even if triggered concurrently. This prevents interference between unrelated operations like saving a profile and uploading an avatar. ```html ``` -------------------------------- ### Submitting Form Data with Actions Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use the 'form' option to submit an existing HTML form. HyperDjango automatically reads the form's method and action URL. ```html
    {% csrf_token %}
    ``` -------------------------------- ### Providing CSRF Source Source: https://hyperdjango.charingcrosscapital.com/docs/base-template Include a hidden div with the CSRF token for the runtime to read, or provide an equivalent. ```html ``` -------------------------------- ### Controlling Request Synchronization (sync: 'replace') Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use 'sync: 'replace'' to cancel and replace any in-flight request in the same coordination lane. Useful for live search inputs. ```html ``` -------------------------------- ### Listen for afterRequest Event Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Add an event listener to the window to capture the 'hyper:afterRequest' event, useful for logging request details. ```javascript window.addEventListener("hyper:afterRequest", (event) => { console.log(event.detail.key, event.detail.ok, event.detail.aborted); }); ``` -------------------------------- ### Delay loading indicator with hyper-loading-delay Source: https://hyperdjango.charingcrosscapital.com/docs/declarative-html-apis Prevent UI flicker by delaying the appearance of a loading indicator. Use `hyper-loading-delay` with a millisecond value to specify how long the indicator should wait before showing. ```html

    Loading...

    ``` -------------------------------- ### Scope loading indicator to action with hyper-loading-action Source: https://hyperdjango.charingcrosscapital.com/docs/declarative-html-apis Control which actions trigger a specific loading indicator by using `hyper-loading-action`. The indicator will only appear when a request with the specified action name is active. ```html

    Searching...

    ``` -------------------------------- ### Rendering Asset Tags in Body Source: https://hyperdjango.charingcrosscapital.com/docs/base-template Place this tag before the end of the body to render any scripts that should be loaded last. ```html {% hyper_body_scripts %} ``` -------------------------------- ### Pass request key directly with hyper-loading Source: https://hyperdjango.charingcrosscapital.com/docs/declarative-html-apis You can directly specify the request key for a loading indicator using the `hyper-loading` attribute itself. This provides a concise way to scope the indicator to a specific request key. ```html

    Searching...

    ``` -------------------------------- ### Add classes during loading with hyper-loading-class Source: https://hyperdjango.charingcrosscapital.com/docs/declarative-html-apis Apply CSS classes to an element while a request is active. Use `hyper-loading-class` to dynamically change the element's appearance during loading states. ```html
    Content
    ``` -------------------------------- ### Listen for streamEvent Event Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Handle 'hyper:streamEvent' to process real-time data pushed from the server. ```javascript window.addEventListener("hyper:streamEvent", (event) => { console.log(event.detail.event, event.detail.data); }); ``` -------------------------------- ### Scope loading indicator to key with hyper-loading-key Source: https://hyperdjango.charingcrosscapital.com/docs/declarative-html-apis Limit a loading indicator's visibility to requests with a specific key. Use `hyper-loading-key` to ensure the indicator only shows for a particular type of request, identified by its key. ```html

    Searching...

    ``` -------------------------------- ### Dispatch Custom Event Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions Use `Event` to dispatch a custom event on a specified target element or the window. It can include a payload. ```python from hyperdjango.actions import Event # Example usage: Event(name='my-custom-event', payload={'data': 123}, target='#my-element') ``` -------------------------------- ### Executing Code Before Submission Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use 'onBeforeSubmit' to run client-side JavaScript code immediately before an action request is sent. This is useful for validation or logging. ```html ``` -------------------------------- ### Load JavaScript Dynamically Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions Use `LoadJS` to dynamically load a JavaScript module script after the action response is received by the client. ```python from hyperdjango.actions import LoadJS # Example usage: LoadJS(src='/static/js/my-module.js') ``` -------------------------------- ### Dispatching Custom Browser Events with Event Source: https://hyperdjango.charingcrosscapital.com/docs/actions Use `Event(...)` to dispatch a browser `CustomEvent`. This is useful for triggering client-side JavaScript logic in response to server-side actions. ```python from __future__ import annotations from hyperdjango.actions import Event, action from hyperdjango.page import HyperView class PageView(HyperView): @action def save_profile(self, request): return [Event(name="profile:saved", payload={"message": "Saved"}, target="#panel")] ``` -------------------------------- ### Controlling Request Synchronization (sync: 'block') Source: https://hyperdjango.charingcrosscapital.com/docs/client-side-actions Use 'sync: 'block'' to ignore new requests while one is active. This is the default for form-backed calls and useful for preventing duplicate submissions. ```html ``` -------------------------------- ### Pass disable key directly with hyper-loading-disable Source: https://hyperdjango.charingcrosscapital.com/docs/declarative-html-apis Specify the request key for disabling a control directly within the `hyper-loading-disable` attribute. This offers a concise method for scoping the disable behavior to a specific request key. ```html ``` -------------------------------- ### render_template_block() Source: https://hyperdjango.charingcrosscapital.com/docs/pages-and-rendering Use `render_template_block()` when you only need one block from a standalone template class. This function allows rendering a specific block of a template with a given context. ```APIDOC ## `render_template_block()` ### Description Use `render_template_block()` when you only need one block from a standalone template class. ### Parameters - **request** (HttpRequest) - Required - The Django HttpRequest object. - **template_class** (Template Class) - Required - The standalone template class to render. - **block_name** (string) - Required - The name of the template block to render. - **context** (dict) - Optional - A dictionary of context variables to pass to the template. ### Returns - **HttpResponse** - An HttpResponse object containing the rendered template block. ``` -------------------------------- ### `Signals(values)` Action Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions Patches multiple Alpine.js signal values simultaneously. ```APIDOC ## `Signals(values)` Action ### Arguments * `values: dict[str, Any]` ### Behavior * patches multiple Alpine values at once ### Event emitted to the client runtime * `patch_signals` ``` -------------------------------- ### HyperView render Signature Source: https://hyperdjango.charingcrosscapital.com/docs/reference/pages-and-rendering Signature for the render method in HyperView. Use this to render the HTML string for a page, optionally specifying a relative template name and context updates. ```python def render( self, *, request: HttpRequest, relative_template_name: str = "", context_updates: dict[str, Any] | None = None, ) -> str: ... ``` -------------------------------- ### `Delete(target)` Action Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions An action that translates into an HTML patch with `swap="delete"`, effectively removing an element from the DOM. ```APIDOC ## `Delete(target)` Action ### Arguments * `target: str` ### Behavior * translated into an HTML patch with `swap="delete"` ### Event emitted to the client runtime * `patch_html` ``` -------------------------------- ### Actions Wrapper Source: https://hyperdjango.charingcrosscapital.com/docs/reference/actions The `Actions` wrapper can be used to group multiple typed action items. It is functionally equivalent to returning a list of action items. ```python from hyperdjango.actions import Actions # Usage example would go here, but is not provided in the source. ```