Code

Opened 2 years ago

Closed 15 months ago

#17683 closed Bug (fixed)

`BaseModelFormSet` ignore form's widgets options when adding the pk field

Reported by: charettes Owned by: charettes
Component: Forms Version: master
Severity: Normal Keywords: basemodelformset widget
Cc: charette.s@… Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

When defining a custom widget for the pk field of a modelform used in a modelformset this way:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
          'id': forms.HiddenInput(attrs={'class': 'a-useful-class'})
        }

MyFormSet = modelformset_factory(MyModel, MyModelForm)

The specified widget is ignored because of this line.

It should be replaced by something along

widget = form._meta.widgets.get(self._pk_field.name, HiddenInput)
form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=widget)

I'll provide patch with tests if this gets accepted.

Attachments (1)

ticket-17683-basemodelformset-pk-widget-v1.diff (3.2 KB) - added by charettes 2 years ago.
Fix with tests

Download all attachments as: .zip

Change History (7)

comment:1 Changed 2 years ago by aaugustin

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Type changed from Uncategorized to Bug

comment:2 Changed 2 years ago by claudep

  • Needs tests set
  • Triage Stage changed from Unreviewed to Accepted

I see no reason why the pk field wouldn't respect the widgets dict. Patch welcome!

Changed 2 years ago by charettes

Fix with tests

comment:3 Changed 2 years ago by charettes

  • Cc charette.s@… added
  • Has patch set
  • Needs tests unset

Added patch with tests. Note that I also corrected regressiontests.model_formsets.regress.CustomWidget (introduced for #13095) to actually be a widget and not a field subclass.

comment:4 Changed 2 years ago by Fandekasp

  • Triage Stage changed from Accepted to Ready for checkin

Good

comment:5 Changed 15 months ago by charettes

  • Owner changed from nobody to charettes
  • Status changed from new to assigned

comment:6 Changed 15 months ago by Simon Charette <charette.s@…>

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

In a097ee32d8364045a950d6a36b19630fc34397f1:

Fixed #17683 -- Make sure BaseModelFormSet respects defined widgets.

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.