# 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](/docs/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.

```interlace-demo
ContactFormDemo
```

### 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**

```python
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**

```django
<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.fields` is 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](/docs/working-with-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.

```interlace-demo
ValidationRulesDemo
```

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](/docs/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 custom `clean()` methods or forms you'll reuse, create a Django Form class instead.
