Forms
Carry a Django Form or ModelForm as component state and bind straight to its fields; Interlace
handles serialization, validation, and data binding. For lighter cases you can skip the Form class and
define inline rules() instead. Full validation details, errors, and custom messages live on the
Validation page.
Using Django forms
Use Django's Form and ModelForm classes as component properties. Interlace automatically handles serialization, validation, and data binding.
Try filling out and submitting this form. Notice validation happens when you click submit.
from django import forms
from interlace import Component
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea, min_length=10)
class ContactFormDemo(Component):
success_message: str = ""
def mount(self):
self.form = ContactForm()
def submit(self):
if self.form.is_valid():
data = self.form.cleaned_data
self.success_message = f"Thanks {data['name']}!"
self.form = ContactForm()
<div>
{% if success_message %}
<div class="success">{{ success_message }}</div>
{% endif %}
<input lace:model="form.name" placeholder="Your name" />
{% if form.errors.name %}
<span class="error">{{ form.errors.name.0 }}</span>
{% endif %}
<input lace:model="form.email" type="email" />
{% if form.errors.email %}
<span class="error">{{ form.errors.email.0 }}</span>
{% endif %}
<textarea lace:model="form.message"></textarea>
<button lace:click="submit">Send Message</button>
</div>
Editing a model with a ModelForm
A ModelForm works the same way, and it's the recommended way to
edit a model. Bind to form.<field>, then call
form.save() to write the cleaned values back to the instance.
PostEditor.py
from django import forms
from interlace import Component
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "content"] # the writable allowlist - nothing else binds
class PostEditor(Component):
form: PostForm = None # declare it: an attribute assigned only in mount() isn't tracked state
saved: bool = False
def mount(self, post_id):
post = Post.objects.get(pk=post_id)
if post.author_id != self.request.user.id: # re-authorise the row
raise PermissionError
self.form = PostForm(instance=post)
def save(self):
if self.form.is_valid():
self.form.save() # writes cleaned fields back to the model
self.saved = True
post_editor.html
<form>
<input lace:model="form.title" />
{% if form.errors.title %}<span class="error">{{ form.errors.title.0 }}</span>{% endif %}
<textarea lace:model="form.content"></textarea>
{% if form.errors.content %}<span class="error">{{ form.errors.content.0 }}</span>{% endif %}
<button lace:click="save">Save</button>
</form>
Why a ModelForm is the safe way to edit a model
Meta.fieldsis exactly Django's mass-assignment guard - the client can only write the fields you list.- The bound instance's primary key rides in checksum-protected metadata and can't be repointed by a field binding, so the client can't pivot the form to another row.
- Edits persist correctly across round-trips (the form re-applies its data over the fetched instance).
See Models for the alternatives and trade-offs.
Inline validation rules
For simple forms without creating a separate Form class, define validation rules directly on your component using the rules() method.
This provides a lightweight alternative to Django Forms.
A lightweight approach to validation. Try submitting with empty or invalid data.
from django import forms
from interlace import Component
class ValidationRulesDemo(Component):
name: str = ""
email: str = ""
age: int = 0
def rules(self):
return {
'name': forms.CharField(
min_length=3,
error_messages={'min_length': 'Min 3 characters'}
),
'email': forms.EmailField(),
'age': forms.IntegerField(
min_value=18,
error_messages={'min_value': 'Must be 18+'}
),
}
def submit(self):
if self.validate():
self.reset()
<div>
<input lace:model="name" placeholder="Your name" />
{% if errors.name %}
<span class="error">{{ errors.name.0 }}</span>
{% endif %}
<input lace:model="email" type="email" placeholder="Email" />
{% if errors.email %}
<span class="error">{{ errors.email.0 }}</span>
{% endif %}
<input lace:model="age" type="number" placeholder="Age" />
{% if errors.age %}
<span class="error">{{ errors.age.0 }}</span>
{% endif %}
<button lace:click="submit">Submit</button>
</div>
Define rules() returning a dict of property names to Django form fields, call validate() in your
action (cleaned data if valid, None if not), and read errors as {{ errors.field_name.0 }}. See
Validation for validate_only(), add_error(), and custom messages.
When to use validation rules
Use
rules()for simple forms that don't need complex validation logic or reuse across components. For complex forms with customclean()methods or forms you'll reuse, create a Django Form class instead.