Opened 4 months ago

Closed 4 weeks ago

#37145 closed Bug (fixed)

ModelFormSet breaks when changing prefix format

Reported by: Jort Roelofs Owned by: diaxoaine
Component: Forms Version: dev
Severity: Normal Keywords: ModelFormSet, add_prefix
Cc: Clifford Gama Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I've been trying to change the way the widget prefixes are formatted to make it work nicely with some JavaScript libraries. Here I ran into the following bug.

class BookForm(forms.ModelForm):
class Meta:
...

def add_prefix(self, field_name)
# Here I use a period as separator instead of a dash.
return f"{self.prefix}.{field_name}" if self.prefix else field_name

BookFormSet = modelformset_factory(Book, form=BookForm)

So far so good, this renders the way I expect it to. However, form submission doesn't work, as the check for the primary key is hardcoded to use a dash as separator ​here. When looking for a primary key, it constructs a key with pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name), but this is inconsistent when the form itself has defined a different way to construct prefixes.

Change History (6)

comment:1 by Clifford Gama, 4 months ago

Cc: Clifford Gama added
Keywords: ModelFormSet add_prefix added; formset removed
Triage Stage: Unreviewed → Accepted
Version: 6.0 → dev

Thanks for the report! I verified that overriding add_prefix on FormSet works, so this bug is only scoped to ModelFormSet. (We may also need to add tests for FormSet as well.)

Would you like to prepare a patch?

comment:2 by diaxoaine, 4 months ago

Owner: set to diaxoaine
Status: new → assigned

comment:3 by diaxoaine, 4 months ago

Has patch: set

comment:4 by Clifford Gama, 4 months ago

Patch needs improvement: set

comment:5 by Clifford Gama, 6 weeks ago

Patch needs improvement: unset
Triage Stage: Accepted → Ready for checkin

comment:6 by Sarah Boyce <42296566+sarahboyce@…>, 4 weeks ago

Resolution: → fixed
Status: assigned → closed

In be6a149:

Fixed #37145 -- Made ModelFormSet respect custom Form.add_prefix().

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