Django

Code

Ticket #7289 (closed: fixed)

Opened 7 months ago

Last modified 3 months ago

ModelForm metaclass doesn't remove declared Field attributes

Reported by: Daniel Pope <dan@mauveinternet.co.uk> Assigned to: nobody
Milestone: 1.0 Component: Forms
Version: SVN Keywords:
Cc: Triage Stage: Accepted
Has patch: 1 Needs documentation: 0
Needs tests: 0 Patch needs improvement: 0

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

modelform_attribute_removal.diff (0.7 kB) - added by Daniel Pope <dan@mauveinternet.co.uk> on 05/22/08 06:38:24.
Patch to allow get_declared_fields to remove fields from attrs

Change History

05/22/08 06:38:24 changed by Daniel Pope <dan@mauveinternet.co.uk>

  • attachment modelform_attribute_removal.diff added.

Patch to allow get_declared_fields to remove fields from attrs

08/08/08 14:33:55 changed by ericholscher

  • needs_better_patch changed.
  • needs_docs changed.
  • stage changed from Unreviewed to Design decision needed.
  • needs_tests changed.
  • milestone set to 1.0.

08/08/08 16:28:35 changed by jacob

  • stage changed from Design decision needed to Accepted.

08/27/08 03:06:00 changed by mtredinnick

  • status changed from new to closed.
  • resolution set to fixed.

(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.


Add/Change #7289 (ModelForm metaclass doesn't remove declared Field attributes)




Change Properties
Action