You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/source/templates.md
+56Lines changed: 56 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -116,6 +116,62 @@ component state. As a result morphdom will clear the input's value.
116
116
Use `items.{{ forloop.counter0 }}.name` instead.
117
117
```
118
118
119
+
## Rendering choice fields
120
+
121
+
Django models often use `TextChoices` (or `IntegerChoices`) to constrain a field to a fixed set of values. To render a reactive `<select>` that is bound to a Unicorn component field, expose the choices list as a component attribute and exclude it from the JavaScript context (since the choices are static and do not need to be reactive).
122
+
123
+
```python
124
+
# new_course.py
125
+
from django_unicorn.components import UnicornView
126
+
from curriculum.models import Course
127
+
128
+
129
+
classNewCourseView(UnicornView):
130
+
grade_level = Course.GradeLevel.UNDEFINED
131
+
subject = Course.Subject.UNDEFINED
132
+
133
+
# Static choices — kept out of the JSON state sent to the browser
Adding the choices to [`Meta.javascript_exclude`](views.md#javascript_exclude) keeps them in the Django template context (so the `{% for %}` loop works) without serialising them into the `unicorn:data` JSON attribute on every render. The `grade_level` and `subject` fields remain fully reactive — Unicorn syncs the selected value back to the component on each change.
167
+
168
+
```{note}
169
+
If you also need validation, set `form_class` on the component to a Django `ModelForm` or `Form`.
170
+
Unicorn will validate `grade_level` and `subject` against the form's field definitions when
171
+
`$validate` is called or when an action method calls `self.validate()`. See
0 commit comments