Opened 12 years ago

Closed 12 years ago

#3810 closed (fixed)

Widgets should take a copy of the attrs dict

Reported by: Chris Beaven Owned by: Adrian Holovaty
Component: Forms Version: master
Severity: Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


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:

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

Change History (5)

comment:1 Changed 12 years ago by Gary Wilson <gary.wilson@…>

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

comment:2 Changed 12 years ago by Chris Beaven

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)

comment:3 Changed 12 years ago by Malcolm Tredinnick

Triage Stage: UnreviewedAccepted

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.

comment:4 Changed 12 years ago by Malcolm Tredinnick

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

comment:5 Changed 12 years ago by Malcolm Tredinnick

Resolution: fixed
Status: newclosed

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

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