Form metaclasses, bound data, and widgets
How does DeclarativeFieldsMetaclass collect declared fields, why does BaseForm 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, which subclasses MediaDefiningClass. When Python executes class NoteForm(forms, DeclarativeFieldsMetaclass runs three steps:
- Pop declared fields: Scans
"attrs"for every value whereisinstance(value, Field), removes each one from"attrs"("attrs.pop(key)"— so"NoteFormdoes not exist as a class attribute!), and stores them in.headline" "attrs['declared_fields']". - Walk the MRO bottom-up: Iterates
reversed(new_classso subclass fields override parent fields while preserving declaration order. Notice lines 42–44: if a subclass sets.__mro__) "some_field = None"in its class body,DeclarativeFieldsMetaclassdeletes"some_field"from"declared_fields"— letting subclasses cleanly drop inherited form fields! - Publish
"base_fields": Assigns the finished dictionary to both"new_classand.base_fields" "new_class..declared_fields"
Now look at BaseForm:
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), 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 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:
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 lazily builds and caches a BoundField in "self via 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"isTrue, preventing client-side tampering on disabled inputs!), and validation rules. - The HTML widget: handles both directions of the HTML boundary —
Widgetextracts raw strings (or lists/files) out of.value_from_datadict "request.POST"/"request.FILES"during validation, whileBoundFieldcomputes the display value (.as_widget BoundField.valuechooses raw submitted"data"when bound so invalid input is preserved for the user to fix, or"initial"when unbound!) and callsWidget.render, which renders the widget’s template through the form renderer and returns aSafeStringviamark_safe!
Watch "StoryForm, per-instance deep-copying, BoundField caching with "prefix='draft'", and TextInput rendering live on "desk/":
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 injected "maxlength" from the model field’s max_length=160, and BoundField 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.