Code

Opened 6 years ago

Closed 6 years ago

Last modified 3 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: UI/UX:

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@…> 6 years ago.
Patch to allow get_declared_fields to remove fields from attrs

Download all attachments as: .zip

Change History (5)

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

Patch to allow get_declared_fields to remove fields from attrs

comment:1 Changed 6 years ago by ericholscher

  • milestone set to 1.0
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Design decision needed

comment:2 Changed 6 years ago by jacob

  • Triage Stage changed from Design decision needed to Accepted

comment:3 Changed 6 years ago by mtredinnick

  • Resolution set to fixed
  • Status changed from new to closed

(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 3 years ago by jacob

  • milestone 1.0 deleted

Milestone 1.0 deleted

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.