Code

Opened 7 years ago

Closed 7 years ago

#3810 closed (fixed)

Widgets should take a copy of the attrs dict

Reported by: SmileyChris Owned by: adrian
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: UI/UX:

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 (0)

Change History (5)

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

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

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

comment:2 Changed 7 years ago 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)

comment:3 Changed 7 years ago by mtredinnick

  • Triage 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.

comment:4 Changed 7 years ago by mtredinnick

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

comment:5 Changed 7 years ago by mtredinnick

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

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

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.