### Install and Scaffold HyperDjango
Source: https://github.com/devwaseem/hyperdjango/blob/main/README.md
Install the hyperdjango package and then use the hyper_scaffold command to set up a new project structure.
```bash
pip install hyperdjango
python manage.py hyper_scaffold
```
--------------------------------
### Loading Example with Scoped Indicators and Controls
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/declarative-html-apis.md
This example demonstrates a common loading pattern using scoped loading indicators and disabled controls based on request keys and delays.
```html
Searching...
```
--------------------------------
### Install Development Dependencies
Source: https://github.com/devwaseem/hyperdjango/blob/main/README.md
Install the development dependencies for hyperdjango, including optional extras.
```bash
pip install -e .[dev]
```
--------------------------------
### Install HyperDjango Dependencies
Source: https://github.com/devwaseem/hyperdjango/blob/main/example/README.md
Install the necessary Python dependencies for HyperDjango. This includes setting up a virtual environment and installing the package in editable mode.
```bash
python -m venv .venv
source .venv/bin/activate
pip install -e .
```
--------------------------------
### Scaffold a Starter Project
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/installation.md
Use the 'hyper_scaffold' management command to create a basic HyperDjango project structure, including Vite configuration and example files.
```bash
python manage.py hyper_scaffold
```
--------------------------------
### Action Returning HttpResponse
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
An `HttpResponse` can be returned directly. This example returns a plain text response for a download action.
```python
from __future__ import annotations
from django.http import HttpResponse
from hyperdjango.actions import action
from hyperdjango.page import HyperView
class PageView(HyperView):
@action
def download(self, request):
return HttpResponse("ok", content_type="text/plain")
```
--------------------------------
### Minimal Custom Base Template Example
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
An example of a minimal custom base template for full control. It includes necessary HyperDjango template tags for assets and scripts, and CSRF token handling.
```django
{# Minimal custom base if you need full control #}
{% load static hyper_tags %}
{{ title|default:"My App" }}
{% hyper_preloads %}
{% hyper_stylesheets %}
{% hyper_head_scripts %}
{% csrf_token %}
{% block body %}{% endblock body %}
{% hyper_body_scripts %}
```
--------------------------------
### Action Returning List of Items
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
Use a list of action items when the entire response is known immediately. 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"}),
]
```
--------------------------------
### Install HyperDjango Package
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/installation.md
Install the HyperDjango package using pip. This is the first step to integrating HyperDjango into your Django project.
```bash
pip install hyperdjango
```
--------------------------------
### Build Server-Driven UI Actions
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/client-side-actions.md
Construct a list of actions to be returned from the server, including HTML content updates and history modifications. This example demonstrates updating search results and the URL.
```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}"),
]
```
--------------------------------
### About Page Inheriting Base Layout
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
An example of a page that inherits from the `BaseLayout`, demonstrating how to extend layout functionality for specific pages.
```python
# hyper/routes/about/+page.py — inheriting the layout
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"}
```
--------------------------------
### Dashboard PageView with Context and Data
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Example of a HyperView for a dashboard page. It uses `get_context` for shared data and `get` to fetch and return specific items for the template.
```python
# hyper/routes/dashboard/index/+page.py
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]:
# Runs on every request (GET and actions). Good for shared data.
context = super().get_context(request)
context["user_name"] = request.user.get_full_name()
return context
def get(self, request: HttpRequest) -> dict[str, object]:
return {
"title": "Dashboard",
"items": list(Item.objects.filter(owner=request.user).order_by("-created")),
}
```
--------------------------------
### Ordered Multi-Patch Updates
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/cookbook.md
This example shows how to perform multiple HTML patches in a specific order. The `swap='outer'` option replaces the target element entirely, while other patches might append or update content.
```python
from __future__ import annotations
from hyperdjango.actions import HTML
return [
HTML(content="A", target="#one"),
HTML(content="
B
", target="#two", swap="outer"),
]
```
--------------------------------
### Action Returning String
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
A string return value is treated as an HTML patch. This example returns a simple div.
```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
"
```
--------------------------------
### Define a Basic Action
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
An action is a method marked with `@action`. 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")]
```
--------------------------------
### Action Returning Generator of Items
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
Use a generator when action items should be streamed over time. This example simulates a job process with status updates, a toast, and a 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="
", target="#job-status")
sleep(1)
yield Toast(payload={"type": "success", "message": "Done"})
yield Redirect(url="/done/")
```
--------------------------------
### Local and Global Signals Together
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/alpine-integration.md
This example shows how to update both a local Alpine x-data variable and a global $store.hyper variable simultaneously using HyperDjango 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:
```
--------------------------------
### Action Returning Dictionary for Template Rendering
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
A dictionary is treated as context for block rendering from the current page template. This example returns stats data.
```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}
```
```django
{% block stats %}
{{ count }} total, {{ completed }} completed
{% endblock stats %}
```
--------------------------------
### Minimal Custom Base Template
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/base-template.md
A minimal example of a custom base template that includes all necessary HyperDjango components.
```django
{% load static hyper_tags %}
{{ title|default:"My App" }}
{% hyper_preloads %}
{% hyper_stylesheets %}
{% hyper_head_scripts %}
{% csrf_token %}
{% block body %}{% endblock body %}
{% hyper_body_scripts %}
```
--------------------------------
### Include Entry Point Script for Layout
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/layouts.md
Define the entry point script for the layout, typically used for frontend logic and styling. Ensure necessary frontend frameworks like Alpine.js are imported and started.
```typescript
import Alpine from "alpinejs";
import "./base.css";
Alpine.start();
```
--------------------------------
### Action Returning Single Item
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
A single action item can be returned directly. This example returns 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")
```
--------------------------------
### Action Returning Actions Object
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
The `Actions` object can group multiple action items. This example creates a new list item and shows a success toast.
```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"}),
)
```
--------------------------------
### Vite Manifest File Format Example
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/asset-resolver.md
This JSON structure represents Vite's standard manifest file format, used by HyperDjango in production mode to map source entries to built asset files.
```json
{
"src/entry.js": {
"file": "assets/entry-a1b2c3d4.js",
"src": "src/entry.js",
"isEntry": true,
"imports": ["src/lib.js"],
"css": ["assets/entry-e5f6g7h8.css"]
}
}
```
--------------------------------
### Typed Action Item: HTML Patch
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
Use `HTML(...)` to patch HTML into the page. This example demonstrates patching with specific swap, transition, and focus options.
```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 a Page View Inheriting from Base Layout
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/layouts.md
Create a page view that inherits from the defined `BaseLayout`. Override methods like `get` to provide page-specific data that will be available in the template context.
```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."}
```
--------------------------------
### Scaffold HyperDjango Project Structure
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Use the `hyper_scaffold` management command to generate a starter hyper/ project tree. Options include `--no-wire` to scaffold files only and `--force` to overwrite existing files.
```bash
# Full scaffold with auto-wiring
python manage.py hyper_scaffold
# Scaffold files only — do not touch settings or urls
python manage.py hyper_scaffold --no-wire
# Overwrite existing scaffolded files
python manage.py hyper_scaffold --force
```
--------------------------------
### Scaffold with Force
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/installation.md
Run the scaffold command and overwrite existing files if conflicts arise.
```bash
python manage.py hyper_scaffold --force
```
--------------------------------
### Run Vite and Django Development Servers
Source: https://github.com/devwaseem/hyperdjango/blob/main/example/README.md
Instructions for running the Vite frontend development server and the Django development server. These should be run in separate terminals.
```bash
cd example
npm install
npm run dev
```
```bash
cd example
python manage.py migrate
python manage.py runserver
```
--------------------------------
### Import Rendering Shortcuts
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/pages-and-rendering.md
Import the render_template_block and render_template_page utility functions from hyperdjango.shortcuts.
```python
from hyperdjango.shortcuts import render_template_block, render_template_page
```
--------------------------------
### Configure HyperDjango Asset Settings
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/assets-and-vite.md
Set up directories for frontend assets, Vite output, and the Vite development server URL. Also configures Django's template and static file directories.
```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]
```
--------------------------------
### Server-Side Action Definition
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/client-side-actions.md
Example of a server-side action method defined using the `@action` decorator within a HyperDjango `HyperView` class.
```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):
...
```
--------------------------------
### Scaffold with No Wire
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/installation.md
Run the scaffold command without setting up the initial frontend wireframe.
```bash
python manage.py hyper_scaffold --no-wire
```
--------------------------------
### Typed Action Item: Delete Element
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
Use `Delete(...)` to remove a target element from the page. This example removes a table row based on its ID.
```python
from __future__ import annotations
from hyperdjango.actions import Delete, action
from hyperdjango.page import HyperView
class PageView(HyperView):
@action
def remove_row(self, request, id: int):
return [Delete(target=f"#row-{id}")]
```
--------------------------------
### Create a Toast action
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/actions.md
Use the Toast class to display a toast message to the user. The frontend determines how to render the payload.
```python
from hyperdjango.actions import Toast
# Example usage within an action method:
return Toast(payload="Operation successful!")
```
--------------------------------
### Create a Basic HTML Template
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/installation.md
Create an HTML template file (e.g., `hyper/routes/about/index.html`) that uses the data returned by the page view. This template will be rendered by HyperDjango.
```django
{{ title }}
This page was rendered by HyperDjango.
```
--------------------------------
### Coordinating Requests with Keys
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/client-side-actions.md
Use the `key` option to group related requests into a named coordination lane. This allows `sync` behavior to apply across requests with the same key and enables scoped loading indicators and disable states.
```html
Searching...
```
--------------------------------
### Runtime Browser Events
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
HyperDjango emits CustomEvents on `window` during the request lifecycle, enabling global handling of events like request start, completion, errors, and upload progress.
```APIDOC
## Runtime Browser Events
### Description
HyperDjango emits `CustomEvent`s on `window` throughout the request lifecycle. These events can be used for analytics, global error handling, or custom integrations.
### Event Listeners
#### `hyper:beforeRequest`
- **Fired:** Before a request is sent.
- **Detail:** `{ action: string, url: string }`
#### `hyper:afterRequest`
- **Fired:** After a request has completed.
- **Detail:** `{ key: string, ok: boolean }`
#### `hyper:requestError`
- **Fired:** When a server-side action results in an error.
- **Detail:** `{ status: number, message: string }`
#### `hyper:uploadProgress`
- **Fired:** During file uploads to track progress.
- **Detail:** `{ key: string, progress: number }`
#### `hyper:streamEvent`
- **Fired:** When a Server-Sent Event (SSE) stream receives an event.
- **Detail:** `{ event: string, data: any }`
### Example (JavaScript)
```javascript
window.addEventListener('hyper:beforeRequest', (e) => {
console.log('Starting:', e.detail.action, '→', e.detail.url);
});
window.addEventListener('hyper:requestError', (e) => {
const { status, message } = e.detail;
showToast('error', message || `Error ${status}`);
});
```
```
--------------------------------
### Custom Django View with HyperPageTemplate
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/cookbook.md
This example shows how to use `HyperPageTemplate` within a custom Django view. It allows you to leverage HyperDjango's templating features in standard Django views.
```python
from __future__ import annotations
from hyperdjango.page import HyperPageTemplate
class ProfileCardTemplate(HyperPageTemplate):
pass
```
```python
from __future__ import annotations
from hyperdjango.shortcuts import render_template_page
def profile_card(request):
return render_template_page(
request,
ProfileCardTemplate,
context={"title": "Account", "description": "From custom view"},
)
```
--------------------------------
### Configure Django Settings for HyperDjango
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Configure Django settings to point to the hyper/ directory and Vite output. Ensure HYPER_FRONTEND_DIR, HYPER_VITE_OUTPUT_DIR, and HYPER_VITE_DEV_SERVER_URL are set correctly. Add 'hyperdjango' to INSTALLED_APPS and include HYPER_FRONTEND_DIR in TEMPLATES DIRS and STATICFILES_DIRS.
```python
# settings.py
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
INSTALLED_APPS = [
# ...
"hyperdjango",
]
HYPER_FRONTEND_DIR = BASE_DIR / "hyper" # where routes/, layouts/, templates/ live
HYPER_VITE_OUTPUT_DIR = BASE_DIR / "dist" # Vite build output
HYPER_VITE_DEV_SERVER_URL = "http://localhost:5173/"
HYPER_DEV = DEBUG # True: Vite dev server; False: manifest
TEMPLATES[0]["DIRS"].append(HYPER_FRONTEND_DIR)
STATICFILES_DIRS = [HYPER_VITE_OUTPUT_DIR]
```
--------------------------------
### Window Action Upload with Progress Callback
Source: https://github.com/devwaseem/hyperdjango/blob/main/example/hyper/routes/upload-progress/index.html
Initiates an upload using `window.action` and provides an `onUploadProgress` callback to update a progress bar and status text in real-time. Handles success and error states after the request.
```javascript
window.demoWindowUpload = function () {
const progress = document.getElementById("window-upload-progress");
const status = document.getElementById("window-upload-status");
if (!progress || !status) {
return;
}
window.demoResetUploadStatus("window");
window.action("upload_demo_window", {},
{
form: "#window-upload-form",
method: "POST",
key: "upload-window",
onUploadProgress(detail) {
const percent = detail.progress == null ? 0 : Math.round(detail.progress * 100);
progress.value = percent;
status.textContent = `Status: uploading | ${percent}%`;
},
}
)
.then(() => {
progress.value = 100;
status.textContent = "Status: done | 100%";
})
.catch(() => {
status.textContent = "Status: error | 0%";
});
};
```
--------------------------------
### Update HTML Template for Action
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/installation.md
Modify the HTML template to include interactive elements, such as buttons, that trigger actions defined in the page view. This example shows how to update a count using an 'increment' action.
```django
{{ title }}
Count: {{ count }}
```
--------------------------------
### Create a Redirect action
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/actions.md
Use the Redirect class 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 within an action method:
return Redirect(url="/new-page")
```
--------------------------------
### Listen for Hyper Request Errors
Source: https://github.com/devwaseem/hyperdjango/blob/main/example/hyper/routes/error-demo/index.html
Attach an event listener to `hyper:requestError` to catch specific errors. This example filters by a key and displays a formatted error message and a toast notification for HTTP 403 responses.
```javascript
(function () { window.addEventListener("hyper:requestError", (event) => { if (event.detail.key !== "error-demo") { return; } const target = document.getElementById("error-result"); if (target && event.detail.status === 403 && event.detail.message) { target.innerHTML = `
`; } window.dispatchEvent( new CustomEvent("hyper:toast", { detail: { type: "error", title": `Request failed (${event.detail.status})`, message: "Caught from hyper:requestError after the action raised PermissionDenied.", }, }) ); }); })();
```
--------------------------------
### Synchronizing Repeated Requests (sync: 'none')
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/client-side-actions.md
Use `sync: 'none'` to allow multiple requests to run concurrently without coordination. Suitable for actions that can be triggered rapidly, like sending log messages.
```html
```
--------------------------------
### HyperDjango PageView for Dynamic Routes
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Define a `PageView` class within `+page.py` files to handle dynamic routes. This class inherits from `HyperView` and implements HTTP methods (e.g., `get`) to process requests and return context data for templates.
```python
# hyper/routes/blog/[slug]/+page.py
from __future__ import annotations
from django.http import HttpRequest
from hyperdjango.page import HyperView
class PageView(HyperView):
route_name = "blog_detail" # optional override; default: "hyper_blog_slug"
def get(self, request: HttpRequest, slug: str) -> dict[str, object]:
post = get_object_or_404(Post, slug=slug)
return {"post": post, "title": post.title}
```
--------------------------------
### Multiple Targeted HTML Patches for Side Panel Sync
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/cookbook.md
This action demonstrates updating multiple parts of the UI simultaneously. It appends to a todo list, updates stats, and shows a success toast, ensuring side panels remain in sync.
```python
from __future__ import annotations
from hyperdjango.actions import HTML, Toast, action
@action
def add_todo(self, request, title="", **params):
return [
HTML(content="
", target="#todo-stats"),
Toast(payload={"type": "success", "message": "Added"}),
]
```
--------------------------------
### HyperDjango Settings Configuration
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Typical settings.py configuration for HyperDjango, defining frontend directories and Vite integration. Ensure `BASE_DIR` and `DEBUG` are defined in your settings.
```python
# Typical settings.py configuration
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]
```
--------------------------------
### Configure Frontend Directory
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/settings.md
Set the path to your 'hyper/' directory where frontend routes, layouts, and templates reside. This tells HyperDjango where to find your frontend code.
```python
HYPER_FRONTEND_DIR = BASE_DIR / "hyper"
```
--------------------------------
### save_and_go Action
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Defines a server action to save user profile changes and then redirect the user. It takes a name parameter and returns a Redirect action.
```APIDOC
## save_and_go
### Description
Saves the user's profile name and redirects to the dashboard.
### Method
POST (inferred from @action usage)
### Endpoint
/some/endpoint (inferred, not explicitly defined)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **name** (str) - Optional - The new first name for the user.
### Request Example
```json
{
"name": "John"
}
```
### Response
#### Success Response (200)
- **list** - A list containing action items, primarily a Redirect action.
- **Redirect** (object) - An action to redirect the browser.
- **url** (str) - The URL to redirect to.
#### Response Example
```json
[
{
"type": "redirect",
"url": "/dashboard/"
}
]
```
```
--------------------------------
### Button to Server Action with Local Alpine State Sync
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/cookbook.md
Use this pattern to trigger a server action from a button click and synchronize a local Alpine.js state variable with the server's response. The `Signal` action updates a specific Alpine state variable.
```html
```
--------------------------------
### Trigger Full Browser Navigation
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Use `Redirect` to initiate a full browser navigation to a specified URL. This action should typically be the last one returned if other actions are also being performed.
```python
from __future__ import annotations
from django.http import HttpRequest
from hyperdjango.actions import History, HTML, Redirect, action
from hyperdjango.page import HyperView
class PageView(HyperView):
@action
def finish_checkout(self, request: HttpRequest) -> list:
order = create_order(request)
return [Redirect(url=f"/orders/{order.pk}/confirmation/")]
```
--------------------------------
### Create a Basic HyperDjango Page
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/installation.md
Define a simple page view in `hyper/routes/about/+page.py`. This view returns data that will be used to render the corresponding HTML template.
```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"}
```
--------------------------------
### Enable Development Mode
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/settings.md
Control asset loading between development and production modes. Set to True to use the Vite dev server and '@vite/client', False to load from the built manifest.
```python
HYPER_DEV = DEBUG
```
--------------------------------
### Call Server Action with Plain JavaScript
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/client-runtime.md
Use the `window.action` function for a plain JavaScript equivalent to calling server-side actions. It accepts the action name, data, and optional request options.
```javascript
window.action('post_create', {
title: 'New Post',
content: 'This is the content.'
}, {
sync: 'replace',
onBeforeSubmit: (options) => {
if (!options.data.title) {
alert('Title is required!');
return false;
}
}
})
```
--------------------------------
### Create a History action
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/actions.md
Use the History class to manipulate the browser's history without a full redirect. Use push_url to add an entry or replace_url to replace the current one.
```python
from hyperdjango.actions import History
# Example usage within an action method:
return History(push_url="/history-entry")
```
--------------------------------
### Catch-All Parameter Route
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/routing.md
Uses `[...path]` to capture the remainder of a URL as a single string. This string is then split by '/' to extract individual path components.
```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}
```
--------------------------------
### Import include_routes
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/django-integration.md
Import the `include_routes` function from `hyperdjango.urls`.
```python
from hyperdjango.urls import include_routes
```
--------------------------------
### window.action(name, data, options)
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/client-runtime.md
The plain JavaScript equivalent of the `$action` function, providing the same functionality for direct use in browser environments.
```APIDOC
## window.action(name, data, options)
### Description
Plain JavaScript equivalent of `$action(...)`.
### Arguments
Arguments are the same as `$action(...)`.
```
--------------------------------
### Define a Base Layout Class
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/layouts.md
Inherit from `HyperView` to create a reusable layout. Override `get_context` to provide shared context data to all pages 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
```
--------------------------------
### Load Custom Entry Scripts
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/template-tags.md
Looks for `name.entry.js` or `name.entry.ts` for custom script entries. Raises `FileNotFoundError` if neither exists.
```django
{% hyper_custom_entry "admin" %}
```
--------------------------------
### add_todo Action
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Defines a server action to add a new todo item. It returns HTML to update the UI and a success toast message.
```APIDOC
## add_todo
### Description
Adds a new todo item for the current user.
### Method
POST (inferred from @action usage)
### Endpoint
/some/endpoint (inferred, not explicitly defined)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **title** (str) - Optional - The title of the todo item.
### Request Example
```json
{
"title": "Buy groceries"
}
```
### Response
#### Success Response (200)
- **list** - A list containing action items like HTML patches and toasts.
- **HTML** (object) - Content to be patched into the DOM.
- **content** (str) - The HTML content.
- **target** (str) - The CSS selector for the target element.
- **swap** (str) - The swap mode (e.g., 'append').
- **Toast** (object) - A toast notification.
- **payload** (dict) - Data for the toast message.
- **type** (str) - The type of toast (e.g., 'success').
- **message** (str) - The message content.
#### Response Example
```json
[
{
"type": "html",
"content": "
Buy groceries
",
"target": "#todo-list",
"swap": "append"
},
{
"type": "toast",
"payload": {
"type": "success",
"message": "Added"
}
}
]
```
```
--------------------------------
### Triggering Actions with Vanilla JavaScript
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/client-side-actions.md
Use `window.action` for triggering server-side actions in plain JavaScript. Attach event listeners to elements and call `window.action` with the action name, data, and options.
```html
```
--------------------------------
### Run HyperDjango Tests
Source: https://github.com/devwaseem/hyperdjango/blob/main/README.md
Execute the test suite for hyperdjango using pytest.
```bash
pytest
```
--------------------------------
### Verify HyperDjango Routes in JSON
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/installation.md
Output the HyperDjango routes in JSON format for easier programmatic inspection or integration with other tools.
```bash
python manage.py hyper_routes --json
```
--------------------------------
### Define a basic action
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/actions.md
Use the @action decorator to mark a method as an action. This makes the action discoverable via get_action(name).
```python
@action
def save(self, request):
...
```
--------------------------------
### Import Actions wrapper
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/actions.md
Import the Actions wrapper from the hyperdjango.actions module.
```python
from hyperdjango.actions import Actions
```
--------------------------------
### Action SSE Event: Load JavaScript
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/sse-payloads.md
Loads a JavaScript file from a specified source URL.
```json
{"src": "/script.js"}
```
--------------------------------
### Include Runtime Scripts
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/base-template.md
Include the core HyperDjango runtime script and the Alpine bridge script in your custom base template.
```html
```
--------------------------------
### Assistant Shell Partial
Source: https://github.com/devwaseem/hyperdjango/blob/main/website/hyper/routes/index/partials/examples_agent.html
This partial defines the structure for the assistant's response bubble in the chat thread.
```html
{% verbatim %}
assistant
{% endverbatim %}
```
--------------------------------
### Tool Log Shell Partial
Source: https://github.com/devwaseem/hyperdjango/blob/main/website/hyper/routes/index/partials/examples_agent.html
This partial renders the container for tool messages during the agent's processing. It includes a placeholder for the log text.
```html
{% verbatim %}
{% endverbatim %}
```
--------------------------------
### Create an HTML patch action
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/actions.md
Use the HTML class to create an action that patches HTML content into the DOM. Specify the target element and swap mode.
```python
from hyperdjango.actions import HTML
# Example usage within an action method:
return HTML(content="
New content
", target="#my-element", swap="innerHTML")
```
--------------------------------
### Action Loading Attributes
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/client-runtime.md
Configuration options that control how the client runtime manages the request lifecycle, state, and coordination.
```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.
```
--------------------------------
### Mount HyperDjango Routes with Prefix
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/installation.md
Optionally, mount HyperDjango routes under a specific URL prefix. This allows you to namespace your HyperDjango application.
```python
urlpatterns = [
*include_routes(url_prefix="app"),
]
```
--------------------------------
### Trigger Server Actions with Plain JavaScript
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Use `window.action()` for triggering server-side actions when not using Alpine.js. This provides similar functionality for direct JavaScript integration.
```javascript
// Plain JavaScript (no Alpine)
document.querySelector("#search-btn").addEventListener("click", () => {
const q = document.querySelector("#q").value;
window.action("search", { q }, { key: "live-search", sync: "replace" });
});
```
--------------------------------
### Return Shapes
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/actions.md
Details the recommended and supported return shapes for actions, including lists, generators, and specific types like `str`, `dict`, and `HttpResponse`.
```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
```
--------------------------------
### Redirect Page with Redirect Action
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/actions.md
Use `Redirect(...)` when the interaction should navigate the user away from the current page. Provide the target URL.
```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/")]
```
--------------------------------
### Catch-all Route Handler in HyperDjango
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
This snippet demonstrates a catch-all route handler using HyperView to process dynamic URL paths. It splits the path into parts for further processing.
```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 = [p for p in path.split("/") if p]
return {"raw_path": path, "parts": parts}
```
--------------------------------
### HyperView with get_context()
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/pages-and-rendering.md
Extends HyperView to provide common context variables, such as 'site_name', available on every request for the page.
```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"}
```
--------------------------------
### Rendering Helpers on HyperView in Python
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Use `HyperView`'s `render`, `render_block`, and `render_template` methods within `@action` handlers to render partial templates. These methods help produce HTML content for `HTML(...)` responses, allowing for dynamic updates to specific parts of a page.
```python
# hyper/routes/profile/+page.py
from __future__ import annotations
from django.http import HttpRequest
from hyperdjango.actions import HTML, action
from hyperdjango.page import HyperView
class PageView(HyperView):
def get(self, request: HttpRequest) -> dict[str, object]:
return {"form": ProfileForm(instance=request.user), "title": "Profile"}
@action
def save(self, request: HttpRequest) -> list:
form = ProfileForm(request.POST, instance=request.user)
if not form.is_valid():
# render() — page-local partial by relative path
return [
HTML(
content=self.render(
request=request,
relative_template_name="partials/form.html",
context_updates={"form": form},
),
target="#profile-form",
swap="outer",
focus="first-invalid",
)
]
form.save()
# render_block() — one named block from index.html
return [
HTML(
content=self.render_block(
request=request,
block_name="success_message",
context_updates={"name": form.instance.first_name},
),
target="#profile-panel",
)
]
```
```python
@action
def open_confirm_modal(self, request: HttpRequest) -> list:
# render_template() — a full template package dir with optional entry.ts
partial = self.render_template(
"partials/confirm_modal",
request=request,
context_updates={"title": "Delete account?", "message": "This is permanent."},
)
from hyperdjango.actions import LoadJS
items = [HTML(content=partial.html, target="#modal-root", swap="inner")]
if partial.js:
items.append(LoadJS(src=partial.js))
return items
```
--------------------------------
### Action SSE Event: Redirect
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/sse-payloads.md
Initiates a client-side redirect to a new URL. The 'replace' flag determines if it replaces the current history entry.
```json
{"url": "/new", "replace": false}
```
--------------------------------
### Synchronizing Repeated Requests (sync: 'replace')
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/client-side-actions.md
Use `sync: 'replace'` to cancel any in-flight request in the same coordination lane and execute the new one. Useful for live search or auto-save features.
```html
```
--------------------------------
### Displaying Search Results
Source: https://github.com/devwaseem/hyperdjango/blob/main/website/hyper/routes/index/partials/examples_search.html
This template partial iterates over the `search_results` context variable to display matching items. If no results are found and a query `q` exists, it displays a 'No matches found' message.
```html
{% for result in search_results %}
{{ result }}
{% empty %}
{% if q %}
No matches found for "{{ q }}"
{% endif %}
{% endfor %}
```
--------------------------------
### Configure Vite Output Directory
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/settings.md
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"
```
--------------------------------
### Async Dashboard View with HyperView
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Defines an asynchronous dashboard view using HyperView, fetching data asynchronously. Requires `fetch_dashboard_data` and `process_job` to be defined elsewhere.
```python
from __future__ import annotations
import asyncio
from django.http import HttpRequest
from hyperdjango.actions import HTML, Toast, action
from hyperdjango.page import HyperView
class PageView(HyperView):
async def get(self, request: HttpRequest) -> dict[str, object]:
data = await fetch_dashboard_data(request.user)
return {"title": "Async Dashboard", "data": data}
@action
async def run_async_job(self, request: HttpRequest, job_id: str = ""):
yield HTML(content="
",
target="#status",
)
yield Toast(payload={"type": "success", "message": "Job complete"})
```
--------------------------------
### Using $action for Search
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/alpine-integration.md
This snippet demonstrates how to use the $action magic provided by HyperDjango when Alpine.js is present. It triggers a 'search' action with query parameters.
```html
```
--------------------------------
### Configure Vite Development Server URL
Source: https://github.com/devwaseem/hyperdjango/blob/main/docs/reference/settings.md
Provide the URL for the Vite development server. HyperDjango injects this URL during development to serve assets directly from Vite.
```python
HYPER_VITE_DEV_SERVER_URL = "http://localhost:5173/"
```
--------------------------------
### Display Compiled HyperDjango Routes
Source: https://context7.com/devwaseem/hyperdjango/llms.txt
Use the `hyper_routes` management command to print all compiled route paths and names from your hyper/routes/ tree. Supports human-readable and JSON output, and route prefixing.
```bash
# Human-readable output
python manage.py hyper_routes
# JSON output — useful for scripting or CI assertions
python manage.py hyper_routes --json
# Preview routes as if mounted under a prefix
python manage.py hyper_routes --prefix app
```