Opened 5 years ago

Closed 4 years 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


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(, HiddenInput)
form.fields[] = 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 4 years ago.
Fix with tests

Download all attachments as: .zip

Change History (7)

comment:1 Changed 4 years ago by aaugustin

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

comment:2 Changed 4 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 4 years ago by charettes

Fix with tests

comment:3 Changed 4 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 4 years ago by Fandekasp

  • Triage Stage changed from Accepted to Ready for checkin


comment:5 Changed 4 years ago by charettes

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

comment:6 Changed 4 years 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.

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