# Models

Read Django models and QuerySets in a component, and edit them safely. A model held
as a property is serialized to its primary key and re-fetched from the database on
each request - so how you wire it up to *writes* matters for security.

## Reading models and QuerySets

Assign a model instance or QuerySet in `mount()` (or any action) and render
it like any other property. Reading is always safe - the security questions only arise
when the client can *write* back.

```python
class PostList(Component):
    posts: QuerySet = None
    search: str = ""

    def mount(self):
        self.posts = Post.objects.filter(published=True)

    def updated_search(self, value):
        qs = Post.objects.filter(published=True)
        self.posts = qs.filter(title__icontains=value) if value else qs
```

```django
<input lace:model.live.debounce.300ms="search" placeholder="Search..." />

<div>
    {% for post in posts %}
        <div lace:key="post-{{ post.id }}">
            <h3>{{ post.title }}</h3>
            <p>{{ post.content|truncatewords:20 }}</p>
        </div>
    {% endfor %}
</div>
```

## Editing a model - use a ModelForm (recommended)

The cleanest way to edit a model is to hold a Django `ModelForm` as a
property and bind to its fields. Interlace serializes the form (and its bound model
instance) automatically, and `lace:model="form.title"` writes go through the
form - only fields declared in `Meta.fields` are accepted. The form is your
write-allowlist, your validation, and your save step, all in one.

```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)
        # re-authorise the row before exposing it for editing
        if post.author_id != self.request.user.id:
            raise PermissionError
        self.form = PostForm(instance=post)

    def save(self):
        if self.form.is_valid():
            self.form.save()            # maps cleaned fields back to the model and saves
            self.saved = True
```

```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 this is the default: `Meta.fields` is exactly Django's mass-assignment
guard, so the client can never write a field you didn't list (`is_staff`,
`balance`, …). The model's primary key travels in the snapshot's
checksum-protected metadata and is **not** reassignable from a field
binding - so, unlike direct model binding below, the client cannot pivot the form to a
different row. See [Forms](/docs/forms/) for the full form
workflow and a live demo (`forms.Form` works identically for non-model data).

## Editing without a form - plain properties, map on save

If you don't want a form, bind to plain component properties and copy them onto the
model when you save. Keep the model itself in a `Locked` property so the
client can't reassign which row is loaded.

```python
from interlace import Component, Locked

class PostEditor(Component):
    post: Locked[Post] = None    # readable, but the client can't swap the pk
    title: str = ""
    content: str = ""

    def mount(self, post_id):
        self.post = Post.objects.get(pk=post_id)   # direct assignment bypasses Locked
        self.title = self.post.title
        self.content = self.post.content

    def save(self):
        self.post.title = self.title
        self.post.content = self.content
        self.post.save()
```

```django
<input lace:model="title" />
<textarea lace:model="content"></textarea>
<button lace:click="save">Save</button>
```

## Direct model-field binding (convenience - with care)

You can bind straight to a model field with `lace:model="post.title"`. For
security, model fields are **not bindable by default** - the dotted path
must be on the component's allowlist, declared either explicitly via
`bindable` or implicitly via validation `rules()`:

```python
class PostEditor(Component):
    post: Post = None
    bindable = ["post.title", "post.content"]   # or a field present in rules()

    def mount(self, post_id):
        self.post = Post.objects.get(pk=post_id)

    def save(self):
        # MANDATORY: the client controls which pk is loaded, so re-authorise every action.
        if self.post.author_id != self.request.user.id:
            raise PermissionError
        self.post.save()
```

> **Read this before using direct binding**
>
> - **The allowlist guards fields, not the row.** A model property is
>   public, so a crafted action can reassign it to *any* primary key
>   (coercion loads that row). `bindable` only restricts which
>   *fields* are writable - not which record. You must re-authorise
>   `self.post` in every action.
> - **You can't `Lock` a field-bound model.** Marking the
>   prop `Locked` blocks the whole path, including
>   `post.title` - so re-authorisation is the only defence here. The
>   ModelForm and plain-property patterns above avoid this entirely.
> - **Bound values are visible** in the browser snapshot
>   (tamper-proof via checksum, but readable), so don't bind a
>   field you can't show the user. See [State storage](/docs/state-storage/).
> - **Collections aren't bindable** - only top-level
>   `model.field`. `lace:model="posts.0.title"` is rejected;
>   edit a list with a form per item or plain properties.

## Supported property types

Beyond models and QuerySets, Interlace serializes and coerces `datetime`,
`date`, `UUID`, `Decimal`, Django Forms/ModelForms, and
the usual primitives - driven by each property's type hint. See
[Properties → Type Coercion](/docs/properties/) for the
full list and the coercion rules.

## Synths - serializing custom types

Every non-primitive that survives the round-trip to the browser and back does so
through a **synth**: a small adapter that *dehydrates* a Python value into JSON and
*hydrates* it back into the real object on the next request. Models, QuerySets,
`datetime`, `UUID`, `Decimal`, and Forms are all built-in synths. (The Model synth is
also where the bindable-field allow-list is enforced, only allow-listed fields can be
written back from the client.) A property whose value no synth matches must already be JSON-serializable.

A synth is three methods:

- `match(value)` - can this synth handle that value?
- `dehydrate(value, context)` - return `(json_value, metadata)`. The metadata's `s` key
  is the synth's short code, stamped into the snapshot so hydration knows which synth ran.
- `hydrate(value, metadata, context)` - rebuild the Python object from that JSON.

### Writing your own

Register a `Synth` subclass and Interlace picks it up for any matching value. Here's one
for `timedelta`, which isn't handled out of the box:

```python
import datetime
from interlace.synths import Synth, register_synth

@register_synth
class TimedeltaSynth(Synth):
    short_code = "td"                      # unique, stamped into the snapshot

    @classmethod
    def match(cls, value):
        return isinstance(value, datetime.timedelta)

    def dehydrate(self, value, context):
        return value.total_seconds(), {"s": self.short_code}

    def hydrate(self, value, metadata, context):
        return datetime.timedelta(seconds=float(value))
```

Now a `timedelta` property round-trips like any built-in type:

```python
class Timer(Component):
    elapsed: datetime.timedelta = datetime.timedelta()

    def add_minute(self):
        self.elapsed += datetime.timedelta(minutes=1)   # persists across requests
```

Register synths once at startup, for example in an app's `apps.py` `ready()`, so the
decorator runs before any component renders. Short codes must be unique: registration
raises if two synths claim the same one. The `context` argument carries
`{'component', 'attr_name'}` when you need them (the built-in Model synth uses it to read
the binding allow-list); simple value types can ignore it.
