Opened 3 weeks ago
Last modified 9 days ago
#37145 assigned Bug
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: | Accepted |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | yes |
| 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 (4)
comment:1 by , 2 weeks ago
| Cc: | added |
|---|---|
| Keywords: | ModelFormSet add_prefix added; formset removed |
| Triage Stage: | Unreviewed → Accepted |
| Version: | 6.0 → dev |
comment:2 by , 2 weeks ago
| Owner: | set to |
|---|---|
| Status: | new → assigned |
comment:3 by , 12 days ago
| Has patch: | set |
|---|
comment:4 by , 9 days ago
| Patch needs improvement: | set |
|---|
Thanks for the report! I verified that overriding
add_prefixon FormSet works, so this bug is only scoped toModelFormSet. (We may also need to add tests forFormSetas well.)Would you like to prepare a patch?