Examples
Note that all examples are deliberately left unstyled to present the simplest implementation.
Validation
Plain text (minimum of 3 characters, max of 10)
text
: hello
Number validation
number
: Datetime with property setter
now
: Dec. 13, 2024, 8:44 p.m.now|date:"s"
: 28Actions
Source
<!-- unicorn/templates/unicorn/validation.html -->
{% load unicorn %}
<div>
<style>
[unicorn\:error\:invalid] {
border: 1px solid red !important;
}
[unicorn\:error\:required] {
border: 1px solid red !important;
}
[unicorn\:error\:max_length] {
border: 1px solid red !important;
}
[unicorn\:error\:min_length] {
border: 1px solid red !important;
}
.error {
color: red;
}
.unicorn-errors {
background-color: #feecf0;
color: #cc0f35;
border-radius: 4px;
position: relative;
padding: .25rem 2.5rem 1.25rem 1.5rem;
margin-bottom: 2rem;
}
</style>
<div>
{% unicorn_errors %}
<h2>Plain text (minimum of 3 characters, max of 10)</h2>
<input unicorn:model="text" type="text" id="text"><br />
<code>text</code>: {{ text }}
<h2>Number validation</h2>
<input unicorn:model="number" type="text" id="number"><br />
<code>number</code>: {{ number }}<br />
<h2>Datetime with property setter</h2>
<input unicorn:model="now" type="text" id="now" unicorn:key="now"><br />
<span class="error">{{ unicorn.errors.now.0.message }}</span>
<code>now</code>: {{ now }}<br />
<code>now|date:"s"</code>: {{ now|date:"s" }}<br />
<h2>Actions</h2>
<button unicorn:click="set_text_no_validation">set_text_no_validation()</button>
<button unicorn:click="set_text_with_validation">set_text_with_validation()</button>
<button unicorn:click="$validate">validate()</button>
<!-- <button unicorn:click="$reset">reset()</button>
<button unicorn:click="$refresh">refresh()</button> -->
</div>
</div>
# unicorn/components/validation.py
from django_unicorn.components import UnicornView
from django import forms
from django.utils import timezone
class ValidationForm(forms.Form):
text = forms.CharField(min_length=3, max_length=10)
now = forms.DateTimeField()
number = forms.IntegerField()
class ValidationView(UnicornView):
form_class = ValidationForm
text = "hello"
number = ""
_now = None
@property
def now(self):
self._now = timezone.now()
return self._now
@now.setter
def now(self, val):
self._now = val
def set_text_no_validation(self):
self.text = "no validation"
def set_text_with_validation(self):
self.text = "validation"
self.validate()
def set_number(self, number):
self.number = number