Django 6.1.3

10.4 Templates and forms

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 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 whenever a template or validator touches "form['headline']".

DeclarativeFieldsMetaclass and per-request copy.deepcopy

Open DeclarativeFieldsMetaclass.__new__, which subclasses 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__:

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__ 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__:

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__ lazily builds and caches a BoundField in "self._bound_fields_cache" via Field.get_bound_field. A BoundField is the bridge joining three independent objects:

Watch "StoryForm.base_fields", per-instance deep-copying, BoundField caching with "prefix='draft'", and TextInput rendering live on "desk/":

Recorded on Django 6.1.3 ch10-presentation script
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 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.