Opened 17 years ago

Closed 16 years ago

Last modified 13 years ago

#7289 closed (fixed)

ModelForm metaclass doesn't remove declared Field attributes

Reported by: Daniel Pope <dan@…> Owned by: nobody
Component: Forms Version: dev
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

Description

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

del(form['myfoo'])
del(form.foo)

Attachments (1)

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

Download all attachments as: .zip

Change History (5)

by Daniel Pope <dan@…>, 17 years ago

Patch to allow get_declared_fields to remove fields from attrs

comment:1 by Eric Holscher, 16 years ago

milestone: 1.0
Triage Stage: UnreviewedDesign decision needed

comment:2 by Jacob, 16 years ago

Triage Stage: Design decision neededAccepted

comment:3 by Malcolm Tredinnick, 16 years ago

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 by Jacob, 13 years ago

milestone: 1.0

Milestone 1.0 deleted

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