Django

Code

Ticket #3810 (closed: fixed)

Opened 2 years ago

Last modified 2 years ago

Widgets should take a copy of the attrs dict

Reported by: SmileyChris Assigned to: adrian
Milestone: Component: Forms
Version: SVN Keywords:
Cc: Triage Stage: Accepted
Has patch: 0 Needs documentation: 0
Needs tests: 0 Patch needs improvement: 0

Description

Currently, Widget.__init__ looks like:

    def __init__(self, attrs=None):
        self.attrs = attrs or {}

Which is a problem because if you pass an attrs dict to the Widget it could get modified in place. For example, in Field.__init__

    # Hook into self.widget_attrs() for any Field-specific HTML attributes.
    extra_attrs = self.widget_attrs(widget)
    if extra_attrs:
        widget.attrs.update(extra_attrs)

Although a slight change in logic, it would probably make more sense if Widget copied attrs (if its a dict)

Attachments

Change History

03/29/07 16:58:13 changed by Gary Wilson <gary.wilson@gmail.com>

  • needs_better_patch changed.
  • needs_tests changed.
  • needs_docs changed.

I'm not seeing the problem, could you please explain.

03/31/07 23:56:32 changed by SmileyChris

This issue came up when dealing with someone on IRC (if I recall correctly).

They had something like this for their form:

from django.newforms import *

extra_attrs = {'class': 'special'}
class TestForm(Form):
    field1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs))
    field2 = CharField(widget=TextInput(attrs=extra_attrs))

Which incorrectly renders (with TestForm(auto_id=False).as_p()) to:

<p>Field1: <input type="text" class="special" name="field1" maxlength="10"/></p>
<p>Field2: <input type="text" class="special" name="field2" maxlength="10" /></p>

(note the second maxlength="10", because extra_attrs was changed in place)

03/31/07 23:58:39 changed by mtredinnick

  • stage changed from Unreviewed to Accepted.

Yep. We should be making a copy. That seems to be normal practice in the standard Python libraries: clients pass by reference, consumers copy if they want to change.

04/01/07 00:16:42 changed by mtredinnick

I'm working on this now. It's actually uncovered a slightly deeper bug.

04/01/07 00:26:26 changed by mtredinnick

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

(In [4894]) Fixed #3810 -- In newforms, copy attribute dictionaries before modifying them in place.


Add/Change #3810 (Widgets should take a copy of the attrs dict)




Change Properties
Action