Opened 6 years ago

Closed 6 years ago

Last modified 6 years ago

#30407 closed New feature (wontfix)

Modelform initial values override instance values when both are set.

Reported by: Alper Cugun Owned by: nobody
Component: Forms Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Alper Cugun)

We ran into a bug (on our side) where our data was not being displayed in a ModelForm for existing instance because we were setting both initial values as the instance in the ModelForm.

Digging into the documentation it turns out that for [ModelForm https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#providing-initial-values] initial overrides instance values ("Initial values provided this way will override both initial values from the form field and values from an attached model instance.") whereas for normal [Forms https://docs.djangoproject.com/en/2.2/ref/forms/api/#dynamic-initial-values] initial does not take precedence over bound data ("These values are only displayed for unbound forms, and they’re not used as fallback values if a particular value isn’t provided."). Maybe that's my mistake for thinking a bound Form and a ModelForm with an instance are roughly equivalent.

I tracked this down to [this commit https://github.com/django/django/commit/51dc4ecf943d1dcc044ed956925760f9d480f56c] 12 years ago and it seems that nobody has complained much about this piece of code in the mean time. So maybe it isn't a problem but I think there is something to be said for reversing the precedence in ModelForm.

I've attached a draft diff to fix this.

Attachments (1)

modelform_reverse_initial.diff (1.2 KB ) - added by Alper Cugun 6 years ago.
draft patch

Download all attachments as: .zip

Change History (4)

by Alper Cugun, 6 years ago

draft patch

comment:1 by Alper Cugun, 6 years ago

Description: modified (diff)

comment:2 by Mariusz Felisiak, 6 years ago

Resolution: wontfix
Status: newclosed
Summary: Modelform initial values override instance values when both are setModelform initial values override instance values when both are set.
Type: BugNew feature
Version: 2.2master

This behavior is documented and expected (as you mentioned above), so a change will be backward incompatible. You can start a discussion with your proposal on django-developers if you think that this should be changed.

comment:3 by Alper Cugun, 6 years ago

OK. I think I expected as much. Thanks for clearing this up and at least now it's documented here as well.

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