Opened 10 years ago

Closed 10 years ago

Last modified 7 years ago

#7289 closed (fixed)

ModelForm metaclass doesn't remove declared Field attributes

Reported by: Daniel Pope <dan@…> Owned by: nobody
Component: Forms Version: master
Severity: Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


With normal forms, writing

class FooForm(forms.Form):
    myfoo = forms.CharField()

form = FooForm()

creates a class where form.myfoo gives an attribute error: the CharField is moved to FooForm.base_fields['myfoo'] by the metaclass and deep-copied to form.fields['myfoo'] by the constructor. With an equivalent ModelForm, this doesn't happen and form.myfoo and form.fields['myfoo'] both refer to a CharField instance.

This would be just a slight incompatibility, except that del(form.fields['myfoo']) should remove the field from the form - this is the intended behaviour for standard Forms. With ModelForms, the spurious attribute means that, in a template, {{form.myfoo}} falls back to displaying the repr of the CharField (eg. <django.newforms.fields.CharField object at 0x1fb0a90>) instead of nothing. To delete fields from a ModelForm you need to write


Attachments (1)

modelform_attribute_removal.diff (690 bytes) - added by Daniel Pope <dan@…> 10 years ago.
Patch to allow get_declared_fields to remove fields from attrs

Download all attachments as: .zip

Change History (5)

Changed 10 years ago by Daniel Pope <dan@…>

Patch to allow get_declared_fields to remove fields from attrs

comment:1 Changed 10 years ago by Eric Holscher

milestone: 1.0
Triage Stage: UnreviewedDesign decision needed

comment:2 Changed 10 years ago by Jacob

Triage Stage: Design decision neededAccepted

comment:3 Changed 10 years ago by Malcolm Tredinnick

Resolution: fixed
Status: newclosed

(In [8618]) Fixed #7289 -- Made ModelForms behave like Forms in the sense that Field
objects don't appear as attributes on the final form instance. They continue to
appear as elements of the form_instance.fields mapping.

If you were relying on ModelForms having fields as attributes, then this will
be slightly backwards incompatible. However, normal template usage will see no
change at all.

Patch from Daniel Pope.

comment:4 Changed 7 years ago by Jacob

milestone: 1.0

Milestone 1.0 deleted

Note: See TracTickets for help on using tickets.
Back to Top