---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# Form metaclasses, bound data, and widgets

How does `DeclarativeFieldsMetaclass` collect declared fields, why does `BaseForm.__init__` deep-copy them per request, and how does `BoundField` join a field, its value, and its widget?

Forms mirror models in syntax — you declare `Field` (`django/forms/fields.py:Field`) attributes on a Python class — yet behave completely differently at runtime. A model class attaches descriptors onto the class body; a form class strips declared fields right off the class body into `"base_fields"`, deep-copies them onto every single request instance, and wraps each field in a **`BoundField`** (`django/forms/boundfield.py:BoundField`) whenever a template or validator touches `"form['headline']"`.

## `DeclarativeFieldsMetaclass` and per-request `copy.deepcopy`

Open `DeclarativeFieldsMetaclass.__new__` (`django/forms/forms.py:DeclarativeFieldsMetaclass.__new__`), which subclasses `MediaDefiningClass` (`django/forms/widgets.py:MediaDefiningClass`). When Python executes `class NoteForm(forms.Form):`, **`DeclarativeFieldsMetaclass`** runs three steps:

1. **Pop declared fields:** Scans `"attrs"` for every value where `isinstance(value, Field)`, removes each one from `"attrs"` (`"attrs.pop(key)"` — so `"NoteForm.headline"` does *not* exist as a class attribute!), and stores them in `"attrs['declared_fields']"`.
2. **Walk the MRO bottom-up:** Iterates `reversed(new_class.__mro__)` so subclass fields override parent fields while preserving declaration order. Notice lines 42–44: if a subclass sets `"some_field = None"` in its class body, `DeclarativeFieldsMetaclass` deletes `"some_field"` from `"declared_fields"` — letting subclasses cleanly drop inherited form fields!
3. **Publish `"base_fields"`:** Assigns the finished dictionary to both `"new_class.base_fields"` and `"new_class.declared_fields"`.

Now look at `BaseForm.__init__` (`django/forms/forms.py:BaseForm.__init__`):

```python
self.fields = copy.deepcopy(self.base_fields)
```

Why does Django pay `copy.deepcopy` on every form instantiation? Because view code routinely mutates `"form.fields"` per request — narrowing a `ModelChoiceField`'s queryset to the current tenant (`"form.fields['desk'].queryset = ..."`), toggling `"required = False"`, or adding CSS classes to `"widget.attrs"`. Because `"base_fields"` is shared across the entire worker process, mutating a field without per-instance deep-copying would bleed User A's queryset and widget attributes straight into User B's form! (Each `Widget.__deepcopy__` (`django/forms/widgets.py:Widget.__deepcopy__`) shallow-copies itself and copies `"self.attrs"` so deep-copying a 2-field form costs only `16.2 us` on Django `6.1.3`, while a 7-field `ModelForm` costs `120.0 us`.)

## Bound vs. unbound forms, `BoundField`, and widget rendering

Look at line 88 of `BaseForm.__init__`:

```python
self.is_bound = data is not None or files is not None
```

Passing an *empty* dictionary `"StoryForm({})"` creates a **bound** form (`"is_bound = True"`, which will immediately fail required-field validation!), whereas `"StoryForm()"` or `"StoryForm(None)"` creates an **unbound** form (`"is_bound = False"`, where `is_valid()` always returns `False` without running `full_clean`!).

When a template iterates `"{% for field in form %}"` or accesses `"form['headline']"`, `BaseForm.__getitem__` (`django/forms/forms.py:BaseForm.__getitem__`) lazily builds and caches a **`BoundField`** (`django/forms/boundfield.py:BoundField`) in `"self._bound_fields_cache"` via `Field.get_bound_field`. A `BoundField` is the bridge joining three independent objects:

- **The form instance (`"self.form"`):** supplies `"is_bound"`, `"data"`, `"files"`, `"prefix"` (producing `"html_name = 'draft-headline'"` and `"auto_id = 'id_draft-headline'"`), `"initial"`, `"errors"`, and `"renderer"`.
- **The form field (`"self.field"`):** supplies `"prepare_value"`, `"bound_data"` (returning `"initial"` instead of `"data"` when `"field.disabled"` is `True`, preventing client-side tampering on disabled inputs!), and validation rules.
- **The HTML **widget** (`django/forms/widgets.py:Widget`):** handles both directions of the HTML boundary — `Widget.value_from_datadict` extracts raw strings (or lists/files) out of `"request.POST"` / `"request.FILES"` during validation, while `BoundField.as_widget` (`django/forms/boundfield.py:BoundField.as_widget`) computes the display value (`BoundField.value` chooses raw submitted `"data"` when bound so invalid input is preserved for the user to fix, or `"initial"` when unbound!) and calls `Widget.render` (`django/forms/widgets.py:Widget.render`), which renders the widget's template through the form renderer and returns a `SafeString` via `mark_safe`!

Watch `"StoryForm.base_fields"`, per-instance deep-copying, `BoundField` caching with `"prefix='draft'"`, and `TextInput` (`django/forms/widgets.py:TextInput`) rendering live on `"desk/"`:

```text recording=ch10-presentation
4. Form metaclass, field deep-copying, and BoundField on StoryForm
  StoryForm.base_fields = ['headline', 'slug', 'desk', 'reporter', 'edition', 'priority', 'body']
  per_instance_deepcopy: f1_is_base=False field_obj_shared=False
  BoundField('headline', prefix='draft'): html_name='draft-headline' auto_id='id_draft-headline' widget=TextInput cached=True
  widget_html = '<input type="text" name="draft-headline" maxlength="160" required id="id_draft-headline">'
```

Notice `"maxlength=\"160\""` and `"required"` inside `"widget_html"`: `CharField.widget_attrs` (`django/forms/fields.py:CharField`) injected `"maxlength"` from the model field's `max_length=160`, and `BoundField.build_widget_attrs` added `"required"` automatically because `"use_required_attribute"` defaults to `True`.

Now that a form is bound to incoming `"POST"` strings, how does Django coerce, validate, and clean every field — and what happens to `"cleaned_data"` the instant a single validator raises `ValidationError`? We trace the exact pipeline next in [The full_clean pipeline and ValidationError](validation.md).
