### Install Django and Start Project Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/getting-started.md Install the Django framework and initialize a new Django project. Familiarize yourself with Django's official resources if you are new to it. ```bash python -m pip install Django django-admin startproject project-name . ``` -------------------------------- ### Install Django Unicorn Locally Source: https://github.com/django-commons/django-unicorn/blob/main/DEVELOPING.md Install Django Unicorn in another project for development. Use pip for editable installs or pyproject.toml for path dependencies. ```bash pip install -e ../django-unicorn ``` ```toml django-unicorn = { path="../django-unicorn", develop=true } ``` -------------------------------- ### Run Local Development Server Source: https://github.com/django-commons/django-unicorn/blob/main/DEVELOPING.md Start the local development server for Django Unicorn. ```bash just runserver ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/django-commons/django-unicorn/blob/main/DEVELOPING.md Install pre-commit hooks for development. This ensures code quality and consistency before committing changes. ```bash just install-pre-commit ``` ```bash uv run pre-commit install ``` -------------------------------- ### UnicornView mount() method example Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md The mount method is called when the component is first initialized. Use it to set initial state. ```python from django_unicorn.components import UnicornView class HelloWorldView(UnicornView): name = "original" def mount(self): self.name = "mounted" ``` -------------------------------- ### Build JavaScript Assets Source: https://github.com/django-commons/django-unicorn/blob/main/DEVELOPING.md Install Node.js dependencies and build the JavaScript assets for Django Unicorn. ```bash npm install ``` ```bash npm run build ``` -------------------------------- ### Run Django Development Server Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md Starts the Django development server to view your application. Access it at http://127.0.0.1:8000/. ```sh python manage.py runserver ``` -------------------------------- ### Install Django Unicorn using PDM Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md Add django-unicorn to your project dependencies using PDM. ```sh pdm add django-unicorn ``` -------------------------------- ### Install Django Unicorn using Pipenv Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md Install django-unicorn into your Pipenv managed virtual environment. ```sh pipenv install django-unicorn ``` -------------------------------- ### Install Django Unicorn using pip Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md Use this command to install the django-unicorn package via pip. It's recommended to do this within a virtual environment. ```sh python -m pip install django-unicorn ``` -------------------------------- ### Install Django Unicorn using Poetry Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md Add django-unicorn to your project dependencies using Poetry. ```sh poetry add django-unicorn ``` -------------------------------- ### Install Django Unicorn using Rye Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md Add django-unicorn to your project dependencies using Rye. ```sh rye add django-unicorn ``` -------------------------------- ### Render Basic Unicorn Component Source: https://github.com/django-commons/django-unicorn/blob/main/example/www/templates/www/html-inputs.html Use the `unicorn` template tag to render a component. This example renders the 'html-inputs' component without any arguments. ```django {% unicorn 'html-inputs' %} ``` -------------------------------- ### Install Django Unicorn Source: https://context7.com/django-commons/django-unicorn/llms.txt Add 'django_unicorn' to INSTALLED_APPS and mount the Unicorn URL router in your Django project settings. ```python # settings.py INSTALLED_APPS = [ # ... "django_unicorn", ] ``` ```python # urls.py from django.urls import path, include urlpatterns = [ path("unicorn/", include("django_unicorn.urls")), # ... ] ``` -------------------------------- ### Connecting to a signal Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/signals.md Example of how to connect a receiver function to a Django Unicorn signal using the `@receiver` decorator. ```APIDOC ## Connecting to a signal ```python from django.dispatch import receiver from django_unicorn.signals import component_rendered @receiver(component_rendered) def on_render(sender, component, html, **kwargs): print(f"{component.component_name} rendered {len(html)} bytes") ``` `sender` is always the component **class** (not an instance). Every signal also passes the live `component` instance as a keyword argument, plus any event-specific kwargs documented below. ``` -------------------------------- ### Checkbox Example in Unicorn Template Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/html-inputs.html Demonstrates conditional rendering in a Unicorn template based on a boolean variable. ```django {% if is_checked %}Yes! 🦄{% else %}Nope 🙁{% endif %} ``` -------------------------------- ### Check Python Version Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/getting-started.md Verify that you have Python 3.8 or greater installed. Ensure Python is added to your system's PATH. ```bash python --version ``` -------------------------------- ### Render Unicorn Component with Arguments Source: https://github.com/django-commons/django-unicorn/blob/main/example/www/templates/www/html-inputs.html Pass keyword arguments to a Unicorn component during rendering. This example renders the 'todo' component with a 'hello' argument set to 'world'. ```django {% unicorn 'todo' hello='world' %} ``` -------------------------------- ### Access Component Arguments in Mount Method Source: https://context7.com/django-commons/django-unicorn/llms.txt Initialize component properties using arguments passed from the template tag. This example shows how to set `greeting` and `user_name` based on `component_kwargs`. ```python from django_unicorn.components import UnicornView class ProfileCardView(UnicornView): greeting = "" user_name = "" def mount(self): # component_kwargs populated from template tag kwargs self.greeting = self.component_kwargs.get("greeting", "Hi") self.user_name = self.component_kwargs.get("user_name", "Guest") ``` -------------------------------- ### Basic Pagination Component Logic Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/pagination.md Implement pagination in a Unicorn component by leveraging Django's Paginator. This example shows how to load, paginate, and display movie data, including methods to navigate between pages. ```python # movies.py from django_unicorn.components import UnicornView from django.core.paginator import Paginator from movies_app.models import Movie class MoviesView(UnicornView): items_per_page = 10 page_number = 1 movies = [] class Meta: javascript_exclude = ( "paginator", "page", "page_range", ) def mount(self): self.load_movies() def load_movies(self): # Get all movies qs = Movie.objects.all() # Create paginator paginator = Paginator(qs, self.items_per_page) page = paginator.get_page(self.page_number) # Store results self.movies = list(page.object_list) self.paginator = paginator self.page = page self.page_range = paginator.get_elided_page_range( number=self.page_number, on_each_side=2, on_ends=1 ) def go_to_page(self, page_num): self.page_number = page_num self.load_movies() ``` -------------------------------- ### Individual Template Setup with Unicorn Tags Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md If not using a base template, include the Unicorn template tags directly in each template that requires them. This includes loading tags, CSRF token, and Unicorn scripts. ```html {% load unicorn %} My Page {% unicorn_scripts %} {% csrf_token %}

Welcome

``` -------------------------------- ### Partial DOM Updates HTML Example Source: https://context7.com/django-commons/django-unicorn/llms.txt HTML template demonstrating `unicorn:partial` for targeted updates. Shows updating by ID, key, and multiple targets. ```html
{{ counter }} {{ checked }} {{ checked }}
``` -------------------------------- ### Base Template Setup for Django Unicorn Source: https://context7.com/django-commons/django-unicorn/llms.txt Include {% unicorn_scripts %} in the head and {% csrf_token %} in the body of your base template to enable Unicorn functionality. ```html {% load unicorn %} {% unicorn_scripts %} {% csrf_token %} {% block content %}{% endblock %} ``` -------------------------------- ### UnicornView hydrate() method example Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md The hydrate method is called when the component data is set. Use it to update component state based on incoming data. ```python from django_unicorn.components import UnicornView class HelloWorldView(UnicornView): name = "original" def hydrate(self): self.name = "hydrated" ``` -------------------------------- ### Install Alpine.js and Morph Plugin in Template Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/custom-morphers.md Include Alpine.js and its morph plugin from CDNs in your HTML template before the {% unicorn_scripts %} tag to use the Alpine.js morpher. ```html ```html ... {% unicorn_scripts %} ... ``` ``` -------------------------------- ### Unicorn Component View Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md Defines the Python view class for your Unicorn component. This example sets an initial 'name' property. ```python # myapp/components/hello_world.py from django_unicorn.components import UnicornView class HelloWorldView(UnicornView): name = "World" ``` -------------------------------- ### Basic Polling Setup Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/polling.md Add `unicorn:poll` to the root div to automatically refresh the component every 2 seconds. Polling is inactive when the page is not visible. ```python from django.utils.timezone import now from django_unicorn.components import UnicornView class PollingView(UnicornView): current_time = now() ``` ```html
{{ current_time }}
``` -------------------------------- ### Working with Enums in Unicorn Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/objects.html Display enum values and set enum properties on the component. This example shows how to set the color property to different enum states. ```html {% comment %} Enums Sets color based on `self.color` enum Sets `self.color` to `Color.GREEN` Sets `self.color` to `Color.BLUE` {% endcomment %} color: {{ color }} ``` -------------------------------- ### Valid Unicorn Component HTML Structure Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/templates.md This example demonstrates a valid component structure with a single root `div` element, which is required for Unicorn's DOM diffing algorithm. ```html

Name: {{ name }}
``` -------------------------------- ### UnicornView login_not_required Meta option example Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Set 'login_not_required = True' in the Meta class to allow unauthenticated users to interact with the component when LoginRequiredMiddleware is active. ```python from django_unicorn.components import UnicornView class MyComponent(UnicornView): class Meta: login_not_required = True ``` -------------------------------- ### JavaScript Interop with Unicorn Components Source: https://context7.com/django-commons/django-unicorn/llms.txt Attach custom JavaScript functions to the `window.Unicorn` namespace for Python components to call. This example demonstrates triggering component methods and model synchronization from JavaScript. ```html
``` -------------------------------- ### Polling Component Refresh HTML Example Source: https://context7.com/django-commons/django-unicorn/llms.txt HTML template for a live clock component that polls for updates. Includes a button to toggle polling and displays the current time. ```html

Current time: {{ current_time }}

``` -------------------------------- ### Serve Sphinx Documentation Source: https://github.com/django-commons/django-unicorn/blob/main/DEVELOPING.md Build and serve the Sphinx documentation locally for review. ```bash just docs-serve ``` -------------------------------- ### UnicornView safe Meta option example Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Use the Meta class's 'safe' tuple to allow a field's value to be returned without HTML encoding, preventing XSS attacks when explicitly opted-in. ```html
{{ something_safe }}
``` ```python from django_unicorn.components import UnicornView class SafeExampleView(UnicornView): something_safe = "" class Meta: safe = ("something_safe", ) ``` ```html
{{ something_safe|safe }}
``` -------------------------------- ### Create a New Unicorn Component Source: https://context7.com/django-commons/django-unicorn/llms.txt Use the 'startunicorn' management command to scaffold a new component, creating both the Python view class and the HTML template. ```shell # Creates myapp/components/hello_world.py and myapp/templates/myapp/hello-world.html python manage.py startunicorn myapp hello-world ``` -------------------------------- ### Create a Unicorn Component Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md Use the `startunicorn` management command to generate the necessary files for a new Unicorn component. ```sh python manage.py startunicorn myapp hello-world ``` -------------------------------- ### Create New Unicorn Component Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/cli.md Use the `startunicorn` command to create a new component. Specify the app name and the component name. This will generate the component file and its corresponding template. ```shell python manage.py startunicorn unicorn hello-world ``` -------------------------------- ### Render Unicorn Component with Variable Argument Source: https://github.com/django-commons/django-unicorn/blob/main/example/www/templates/www/html-inputs.html Pass a Django template variable as an argument to a Unicorn component. This example renders the 'todo' component with the 'hello' argument set to the value of the 'example' variable. ```django {% unicorn 'todo' hello=example %} ``` -------------------------------- ### Create Nested Unicorn Component Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/cli.md The `startunicorn` command supports creating components in sub-folders using dot notation. This allows for a more organized structure of your components. ```shell python manage.py startunicorn unicorn hello.world ``` -------------------------------- ### Create Unicorn Components Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/components.md Use the `startunicorn` management command to generate new component files within a specified Django app. Ensure the app is listed in `INSTALLED_APPS`. ```shell python manage.py startunicorn myapp hello-world hello-magic ``` -------------------------------- ### Initialize Unicorn (Non-Minified) Source: https://github.com/django-commons/django-unicorn/blob/main/src/django_unicorn/templates/unicorn/scripts.html Use this snippet for the non-minified build. It imports Unicorn and morpher modules, assigns Unicorn to the global scope, and then initializes Unicorn with configuration. ```html import * as Unicorn from "{% static 'unicorn/js/unicorn.js' %}"; import { getMorpher } from "{% static 'unicorn/js/morpher.js' %}"; // Set Unicorn to the global, so it can be used by components window.Unicorn = Object.assign(window.Unicorn || {}, Unicorn); const url = "{% url 'django_unicorn:message' %}"; const morpherSettings = JSON.parse(document.getElementById("unicorn:settings:morpher").textContent); Unicorn.init(url, "{{ CSRF_HEADER_NAME }}", "{{ CSRF_COOKIE_NAME }}", morpherSettings); {% endif %} ``` -------------------------------- ### Create a Virtual Environment Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/getting-started.md Create a dedicated virtual environment for your project to manage dependencies. This step is recommended when using pip directly. ```bash python -m venv .venv ``` -------------------------------- ### component_args Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Demonstrates how to access arguments passed to a component during initialization. ```APIDOC ## component_args ### Description The arguments passed into the component are available via the `component_args` attribute. ### Template Usage ```html {% unicorn 'hello-arg' 'World' %} ``` ### Component Code ```python from django_unicorn.components import UnicornView class HelloArgView(UnicornView): def mount(self): assert self.component_args[0] == "World" ``` ``` -------------------------------- ### Create a Django App for Unicorn Component Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md Command to create a new Django app. This app will house your Unicorn components and related views/templates. ```sh python manage.py startapp myapp ``` -------------------------------- ### mount() Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md The `mount` method is called when the component is initialized or reset. ```APIDOC ## Instance methods ### mount() Gets called when the component gets initialized or [reset](actions.md#reset). ``` -------------------------------- ### Boolean Toggles in Unicorn Template Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/html-inputs.html Shows conditional rendering for boolean states, including examples with partial key/ID updates. ```django {% if another_check %}Checked ✅{% else %}Not checked ❎{% endif %} ``` -------------------------------- ### Python View for Visibility Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/visibility.md Define a Django Unicorn view with a method to be called when an element becomes visible. This example increments a counter. ```python from django_unicorn.components import UnicornView class VisibilityView(UnicornView): visibility_count = 0 def add_count(self): self.visibility_count += 1 ``` -------------------------------- ### HelloWorldView with template_html Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Defines a Unicorn View with an inline HTML template. ```APIDOC ## HelloWorldView with template_html ### Description Defines a Unicorn View where the HTML template is provided inline as a string. ### Class Definition ```python from django_unicorn.components import UnicornView class HelloWorldView(UnicornView): class Meta: template_html = """
Count: {{ count }}
""" ... ``` ### Note Setting `template_html` directly as a class attribute also works and is supported for backwards compatibility. ``` -------------------------------- ### Synchronize Development Environment Source: https://github.com/django-commons/django-unicorn/blob/main/DEVELOPING.md Synchronize the development environment using uv, including dependencies for minification and documentation. ```bash uv sync --extra minify --extra docs ``` -------------------------------- ### Correct Mutable Initialization Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Shows the recommended approach for initializing mutable objects by setting them in the `mount` method to ensure each component instance has its own state. ```python from django_unicorn.components import UnicornView class SentenceView(UnicornView): words: list[str] # not setting a default value is valid word_counts: dict[str, int] = None # using None for the default is valid def mount(self): self.words = [] # initialize a new list every time a SentenceView is initialized and mounted self.word_counts = {} # initialize a new dictionary every time a SentenceView is initialized and mounted def add_word(self, word: str): ... ``` -------------------------------- ### Wizard Step Rendering with Unicorn Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/wizard/wizard.html Renders different Unicorn components based on the current step. Ensure the 'unicorn' template tag is loaded. ```html {% load unicorn %} {% if step == 1 %} {% unicorn "wizard/step1" id="step1" %} {% elif step == 2 %} {% unicorn "wizard/step2" id="step2" %} {% elif step == 3 %} Last step! {{ step }} Previous Start over {% else %} UNKNOWN STEP! {{ step }} {% endif %} ``` -------------------------------- ### Unicorn Key Bindings Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/text-inputs.html Demonstrates how to bind actions to specific keys using Unicorn's event modifiers. ```html ``` -------------------------------- ### Run Full Test Matrix Source: https://github.com/django-commons/django-unicorn/blob/main/AGENTS.md Execute this command to run the full test matrix locally, simulating GitHub Actions using act. ```bash just test-python-matrix ``` -------------------------------- ### Get Elided Page Range Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/pagination.md Use get_elided_page_range() to display a manageable number of page links for large datasets. Configure pages shown on each side and at the ends. ```python self.page_range = paginator.get_elided_page_range( number=self.page_number, on_each_side=2, # Show 2 pages on each side of current on_ends=1 # Show 1 page at each end ) ``` -------------------------------- ### Get Last Return Value Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/actions.md Retrieve the return value of the last executed action method on a component using `Unicorn.getReturnValue()`. Specify the component name or key. ```html {% unicorn 'hello-world' %} ``` -------------------------------- ### UnicornView javascript_exclude Meta option example Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Use the Meta class's 'javascript_exclude' tuple to prevent an attribute from being exposed to JavaScript while still being available in the Django template. ```html
{% for state in all_states %}
{{ state }}
{% endfor %}
``` ```python from django_unicorn.components import UnicornView class HelloStateView(UnicornView): all_states = ( "Alabama", "Alaska", ... "Wisconsin", "Wyoming", ) class Meta: javascript_exclude = ("all_states", ) ``` -------------------------------- ### UnicornView exclude Meta option example Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Use the Meta class's 'exclude' tuple to prevent specific public attributes from being included in the component's context. ```python from django_unicorn.components import UnicornView class HelloStateView(UnicornView): _all_states = ( "Alabama", "Alaska", ... "Wisconsin", "Wyoming", ) ``` ```python from django_unicorn.components import UnicornView class HelloStateView(UnicornView): all_states = ( "Alabama", "Alaska", ... "Wisconsin", "Wyoming", ) class Meta: exclude = ("all_states", ) ``` -------------------------------- ### HelloWorldView with template_name Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Defines a basic Unicorn View with an external template name. ```APIDOC ## HelloWorldView with template_name ### Description Defines a basic Unicorn View that uses an external HTML file for its template. ### Class Definition ```python from django_unicorn.components import UnicornView class HelloWorldView(UnicornView): class Meta: template_name = "unicorn/hello-world.html" ``` ### Note Setting `template_name` directly as a class attribute also works and is supported for backwards compatibility. ``` -------------------------------- ### Run Linting and Type Checking Source: https://github.com/django-commons/django-unicorn/blob/main/AGENTS.md Execute this command to perform linting and type checking on the project using ruff and ty. ```bash just type ``` -------------------------------- ### Invalid Unicorn Component HTML Structure Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/templates.md A component must have a single root element. This example is invalid because the input and break tags are not wrapped in a single parent element. ```html
Name: {{ name }} ``` -------------------------------- ### Tag a Release Source: https://github.com/django-commons/django-unicorn/blob/main/DEVELOPING.md Tag a new release version in Git. ```bash git tag #.##.# ``` -------------------------------- ### Unicorn Action Chaining Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/text-inputs.html Illustrates chaining multiple actions and event modifiers for complex input handling. ```html ``` -------------------------------- ### Problematic Table Structure with Component Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/table-limitations.md This example shows a common pattern where a component renders elements outside of valid table hierarchy, leading to browser DOM correction and reactivity failures. ```html {% for item in items %} {% unicorn 'row-component' item=item key=item.id %} {% endfor %} ``` ```html {{ item.name }} {% if modal_visible %} {% endif %} ``` -------------------------------- ### component_kwargs Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Demonstrates how to access keyword arguments passed to a component during initialization. ```APIDOC ## component_kwargs ### Description The keyword arguments passed into the component are available via the `component_kwargs` attribute. ### Template Usage ```html {% unicorn 'hello-kwarg' hello='World' %} ``` ### Component Code ```python from django_unicorn.components import UnicornView class HelloKwargView(UnicornView): def mount(self): assert self.component_kwargs["hello"] == "World" ``` ``` -------------------------------- ### Run Python/Django Matrix Unit Tests Source: https://github.com/django-commons/django-unicorn/blob/main/DEVELOPING.md Run Python and Django matrix unit tests using GitHub Actions locally with 'act'. ```bash act -W .github/workflows/python.yml -j test ``` -------------------------------- ### Nest Components in Django Template Source: https://context7.com/django-commons/django-unicorn/llms.txt Render child components within a parent component's template. This example shows a `table` component rendering a `filter` component and multiple `row` components. ```html {% load unicorn %}
{% unicorn 'filter' %} {% for book in books %} {% unicorn 'row' book=book key=book.id %} {% endfor %}
AuthorTitle
``` -------------------------------- ### Rendering Modal Inside a Valid Table Cell Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/table-limitations.md This example demonstrates wrapping a modal within a `` element with `colspan` to maintain valid table structure when rendering modals inside a table. ```html {% if modal_visible %} {% endif %} ``` -------------------------------- ### Calling Component Methods with Keys Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/components.md To invoke a method on a specific component instance, pass its `key` as the first argument to `Unicorn.call()`. ```html ``` -------------------------------- ### Initialize Unicorn (Minified) Source: https://github.com/django-commons/django-unicorn/blob/main/src/django_unicorn/templates/unicorn/scripts.html Use this snippet when the Unicorn JavaScript is minified. It directly initializes Unicorn with the provided URL, CSRF headers, and morpher settings. ```html {% load static %} {{ MORPHER|json_script:"unicorn:settings:morpher" }} {% if MINIFIED %} const url = "{% url 'django_unicorn:message' %}"; const morpherSettings = JSON.parse(document.getElementById("unicorn:settings:morpher").textContent); Unicorn.init(url, "{{ CSRF_HEADER_NAME }}", "{{ CSRF_COOKIE_NAME }}", morpherSettings); {% else %} ``` -------------------------------- ### Passing Enum Values in Unicorn Actions Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/actions.md Enums cannot be passed directly, but their values can. Use enum type annotations for coercion. The HTML example shows how to pass enum values or their raw values to actions. ```python from django_unicorn.components import UnicornView from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 PURPLE = 4 class EnumView(UnicornView): color = Color.RED purple_color = Color.PURPLE def set_color(self, color: Color): self.color = color ``` ```html

Color: {{ color }}
Color int: {{ color.value }}
``` -------------------------------- ### Run JavaScript Tests Source: https://github.com/django-commons/django-unicorn/blob/main/AGENTS.md Execute this command to run the JavaScript tests using npm. ```bash just test-js ``` -------------------------------- ### Bind to Django QuerySet Model Fields Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/django-models.md Access and bind to fields of models within a QuerySet using index and dot notation. This example shows binding to the `title` and `description` fields of books in a QuerySet. ```html
{% for book in books %}
{{ book.title }}
{{ book.description }}
{% endfor %}
``` -------------------------------- ### Select Input Rendering in Unicorn Template Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/html-inputs.html Illustrates how to render a select dropdown using a loop in a Unicorn template. ```django cool -- select -- {% for flavor in flavors %} {{ flavor }} {% endfor %} ``` -------------------------------- ### Custom Pagination UI with Navigation Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/pagination.md Create custom pagination controls using HTML and Unicorn directives for first, previous, next, and last page navigation. ```html ``` -------------------------------- ### Iterate and Display Django Model Data with Unicorn Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/models.html Use the `{% for ... %}` tag to loop through Django model instances and display their attributes within a Unicorn template. This example shows how to access related objects and their properties. ```django {% for flavor in flavors %} #### {{ flavor.pk }} Name {{ flavor.name }} Label {{ flavor.label }} Float {{ flavor.float_value }} Decimal value {{ flavor.decimal_value }} Parent n/a {% for available_flavor in available_flavors %} {{ available_flavor.name }} {% endfor %} {{ flavor.parent.name }} Taste {% for available_taste in available_tastes %} {{ available_taste.name }} {% endfor %} {% for taste in flavor.taste_set.all %}* {{ taste.name }} {% endfor %} save(flavor.pk) delete(flavor.pk) model_typehint(flavor.pk) {% endfor %} ``` -------------------------------- ### Target Multiple Actions Loading State with Wildcard Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/loading-states.md Use an asterisk (*) as a wildcard with `unicorn:target` to apply loading states to multiple elements simultaneously. This is useful for grouping similar actions. ```html
Updating!
``` -------------------------------- ### Basic Pagination Template Rendering Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/pagination.md Render paginated results and navigation controls in an HTML template using Django's template tags and Unicorn directives. This example displays movie titles and provides buttons for navigating through pages. ```html
{% for movie in movies %}

{{ movie.title }}

{{ movie.description }}

{% empty %}

No movies found.

{% endfor %}
{% if page.has_other_pages %} {% endif %}
``` -------------------------------- ### Unicorn Component Methods Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/validation.html Illustrates available methods for interacting with a Unicorn component, including setting text with or without validation, resetting state, and refreshing the view. ```html [set_text_no_validation()](blob) set_text_no_validation() set_text_with_validation() $validate $reset $reset() $refresh ``` -------------------------------- ### Unicorn Calling Python Methods Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/text-inputs.html Shows how to call Python methods from the frontend using Unicorn, passing arguments and event data. ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` -------------------------------- ### Run JavaScript Unit Tests Source: https://github.com/django-commons/django-unicorn/blob/main/DEVELOPING.md Execute JavaScript unit tests for Django Unicorn. ```bash npm run test ``` -------------------------------- ### Run Python Unit Tests Source: https://github.com/django-commons/django-unicorn/blob/main/DEVELOPING.md Execute Python unit tests for Django Unicorn. ```bash just test-python ``` -------------------------------- ### Setting Properties with Shortcuts in Unicorn Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/actions.md Actions can directly set component properties without needing an explicit method. This is useful for simple assignments. ```html
Hello {{ name|title }} 👋
``` ```python # set_shortcut.py from django_unicorn.components import UnicornView class SetShortcutView(UnicornView): name = "World" ``` -------------------------------- ### component_mounted Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/signals.md Sent when a component is first created. Passes the component instance. ```APIDOC ### `component_mounted` Sent when a component is first created (mirrors the {meth}`mount` hook). | kwarg | type | description | |-------|-------|-------------| | `component` | `UnicornView` | The component instance | ``` -------------------------------- ### Define HelloWorldView with template_name Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Define a basic UnicornView by specifying the template_name in the Meta class. This is the standard way to link a view to its HTML template. ```python from django_unicorn.components import UnicornView class HelloWorldView(UnicornView): class Meta: template_name = "unicorn/hello-world.html" ``` -------------------------------- ### Instantiate Custom Types as Arguments Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/actions.md Shows how to use custom Python classes as type annotations for arguments. Unicorn will attempt to instantiate the object with the provided value. ```python # argument_custom_type.py from django_unicorn.components import UnicornView class CustomType: def __init__(self, custom_type_id: int): self.custom_type_id = custom_type_id class ArgumentCustomTypeView(UnicornView): def is_custom_type(self, obj: CustomType): assert type(obj) is CustomType ``` -------------------------------- ### Pass Django Models as Arguments Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/actions.md Demonstrates passing Django User models to component methods, either directly as an argument or via a `pk` keyword argument. ```python # argument_model.py from django_unicorn.components import UnicornView from django.contrib.auth.models import User class ArgumentModelView(UnicornView): def is_user_via_arg(self, obj: User): assert type(obj) is User def is_user_via_kwarg(self, pk: User=None): assert type(obj) is User ``` -------------------------------- ### HTML Template for New Course Form Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/templates.md Renders a form with dropdowns for grade level and subject, and a save button. Uses Unicorn's `unicorn:model` for two-way data binding and `unicorn:click` to trigger the save action. ```html
``` -------------------------------- ### Component Actions: Redirect, Hash Update, Location Update Source: https://context7.com/django-commons/django-unicorn/llms.txt Demonstrates different return types for component actions: server-side redirect, URL hash update, and history API location update. ```python from django.shortcuts import redirect from django_unicorn.components import HashUpdate, LocationUpdate, UnicornView from books.models import Book class BookSaveView(UnicornView): title = "" def save_and_redirect(self): book = Book.objects.create(title=self.title) # Full server-side redirect return redirect(f"/books/{book.id}/") def save_and_hash(self): book = Book.objects.create(title=self.title) # Update URL hash only (no page reload) return HashUpdate(f"#{book.id}") def save_and_pushstate(self): book = Book.objects.create(title=self.title) # Update full URL via history.pushState (no page reload) return LocationUpdate(redirect(f"/books/{book.id}/`), title=book.title) ``` -------------------------------- ### Target Specific Action Loading State by Key Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/loading-states.md Similar to targeting by ID, you can use `unicorn:target` with a `unicorn:key` to control loading element visibility for specific actions. ```html
Updating!
Deleting!
``` -------------------------------- ### Extend Base Template with Unicorn Scripts Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/installation.md Demonstrates how a child template extends a base template that includes Unicorn scripts. ```html {% extends "base.html" %} {% block content %}

Welcome

{% endblock %} ``` -------------------------------- ### Configure Secure Component View Source: https://context7.com/django-commons/django-unicorn/llms.txt Configure component security, template paths, and data exclusion using the Meta class. Use `safe` for unescaped HTML and `login_not_required` to bypass authentication. ```python from django_unicorn.components import UnicornView from .forms import MyForm class SecureView(UnicornView): public_data = "visible in HTML and JS" template_only_data = ("Alabama", "Alaska", "Wyoming") sensitive_html = "bold" class Meta: # Override template path (default: unicorn/.html) template_name = "myapp/custom_template.html" # Or define the template inline: # template_html = "
{{ public_data }}
" # Exclude from both template context and JS exclude = ("template_only_data",) # Available in template but NOT serialized to JS/HTML source javascript_exclude = ("template_only_data",) # Allow HTML to pass through unescaped (XSS risk — use carefully) safe = ("sensitive_html",) # Allow unauthenticated users when LoginRequiredMiddleware is active login_not_required = True # Attach a Django form for validation form_class = MyForm # Set a default component key component_key = "my-secure-view" ``` -------------------------------- ### Custom methods as properties Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Explains how custom methods without arguments can be accessed like properties in the template. ```APIDOC ## Custom methods ### Description Defined component instance methods with no arguments (other than `self`) are available in the Django template context and can be called like a property. ### Component Code ```python from django_unicorn.components import UnicornView class StateView(UnicornView): def all_states(self): return ["Alabama", "Alaska", "Arizona", ...] ``` ### Template Usage ```html
``` ### Caching with `cached_property` If the method is intensive, it can be cached using Django's `cached_property` to prevent duplicate API requests or database queries. The method will only be executed once per component rendering. ```python from django.utils.functional import cached_property from django_unicorn.components import UnicornView class StateView(UnicornView): @cached_property def all_states(self): return ["Alabama", "Alaska", "Arizona", ...] ``` ``` -------------------------------- ### Multiple Select Input Rendering in Unicorn Template Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/html-inputs.html Demonstrates rendering a multiple select input, displaying joined values. ```django Howdy {{ things|join:", " }} ``` -------------------------------- ### Configure Django Unicorn Settings Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/settings.md This dictionary in your settings.py file configures all Unicorn settings. All options are optional. ```python UNICORN = { "ALLOWED_JS_CALL_LIST": ["Unicorn"], "APPS": ["unicorn",], "CACHE_ALIAS": "default", "MINIFY_HTML": False, "MINIFIED": True, "SERIAL": { "ENABLED": False, "TIMEOUT": 60, }, "SCRIPT_LOCATION": "after", "MORPHER": { "NAME": "morphdom", "RELOAD_SCRIPT_ELEMENTS": False, }, } ``` -------------------------------- ### Displaying Datetime Objects in Unicorn Source: https://github.com/django-commons/django-unicorn/blob/main/example/unicorn/templates/unicorn/objects.html Showcase datetime objects and demonstrate helper functions for date manipulation and checking. Type hints can influence how dates are processed. ```html {% comment %} Datetime {% endcomment %} {{ date_example }} get_date check_date static string check_date (c) ``` ```html {% comment %} Datetime with type hint {% endcomment %} {{ date_example_with_typehint }} check_date (c) check_date (U) add_hour() ``` -------------------------------- ### Define a Unicorn Component View Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/direct-view.md Define a simple Unicorn component view by inheriting from `UnicornView` and setting properties. ```python # book.py from django_unicorn.components import UnicornView class BookView(UnicornView): title = "" ``` -------------------------------- ### Call Component Method by Key Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/actions.md Use `Unicorn.call()` with the component's unique key to trigger a method. This is useful when multiple instances of the same component are rendered. ```html {% unicorn 'hello-world' key='hello-universe' %} ``` -------------------------------- ### Call Component Method with Arguments Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/actions.md Pass additional arguments to `Unicorn.call()` to provide parameters for the called method. The arguments are passed after the method name. ```html {% unicorn 'hello-world' %} ``` -------------------------------- ### force_render Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Demonstrates how to force a parent component to re-render. ```APIDOC ## force_render ### Description Forces the component to re-render. This is typically used when a child component needs to trigger a re-render of its parent. ### Component Code ```python from django_unicorn.components import UnicornView class FilterView(UnicornView): search = "" def updated_search(self, query): self.parent.load_table() if query: self.parent.books = list(filter(lambda f: query.lower() in f.name.lower(), self.parent.books)) # Forces the parent to re-render instead of just the current child component self.parent.force_render = True ``` ``` -------------------------------- ### Custom Class Serialization with UnicornField Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/views.md Demonstrates how to serialize a custom class by inheriting from `UnicornField`, which automatically handles serialization using `self.__dict__`. ```python from django_unicorn.components import UnicornView, UnicornField class Author(UnicornField): def mount(self): self.name = 'Neil Gaiman' # Not needed because inherited from `UnicornField` # def to_json(self): # return {'name': self.name} class HelloWorldView(UnicornView): author = Author() ``` -------------------------------- ### Render Text Input Component Source: https://github.com/django-commons/django-unicorn/blob/main/example/www/templates/www/text-inputs.html Use the unicorn template tag to render a text input component. Pass a unique key to differentiate multiple instances. ```html {% unicorn 'text-inputs' key="asdf" %} ``` ```html {% unicorn 'text-inputs' key="zxcv" %} ``` -------------------------------- ### Pass Arguments and Keyword Arguments to a Component Source: https://github.com/django-commons/django-unicorn/blob/main/docs/source/components.md Demonstrates passing positional and keyword arguments to the `unicorn` templatetag. These arguments are accessible within the component's `component_args` and `component_kwargs`. ```html {% load unicorn %} {% csrf_token %} {% unicorn 'hello-world' "Hello" name="World" %} ```