Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed #30534 -- Fixed overriding a field's default in ModelForm.cleaned_data(). #11433

Merged
merged 1 commit into from Jun 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 5 additions & 2 deletions django/forms/models.py
Expand Up @@ -48,8 +48,11 @@ def construct_instance(form, instance, fields=None, exclude=None):
continue
# Leave defaults for fields that aren't in POST data, except for
# checkbox inputs because they don't appear in POST data if not checked.
if (f.has_default() and
form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name))):
if (
f.has_default() and
form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name)) and
cleaned_data.get(f.name) in form[f.name].field.empty_values
):
continue
# Defer saving file-type fields until after the other fields, so a
# callable upload_to can use the values from other fields.
Expand Down
26 changes: 26 additions & 0 deletions tests/model_forms/tests.py
Expand Up @@ -585,6 +585,32 @@ class Meta:
m2 = mf2.save(commit=False)
self.assertEqual(m2.mode, '')

def test_default_not_populated_on_non_empty_value_in_cleaned_data(self):
class PubForm(forms.ModelForm):
mode = forms.CharField(max_length=255, required=False)
mocked_mode = None

def clean(self):
self.cleaned_data['mode'] = self.mocked_mode
return self.cleaned_data

class Meta:
model = PublicationDefaults
fields = ('mode',)

pub_form = PubForm({})
pub_form.mocked_mode = 'de'
pub = pub_form.save(commit=False)
self.assertEqual(pub.mode, 'de')
# Default should be populated on an empty value in cleaned_data.
default_mode = 'di'
for empty_value in pub_form.fields['mode'].empty_values:
with self.subTest(empty_value=empty_value):
pub_form = PubForm({})
pub_form.mocked_mode = empty_value
pub = pub_form.save(commit=False)
self.assertEqual(pub.mode, default_mode)

def test_default_not_populated_on_optional_checkbox_input(self):
class PubForm(forms.ModelForm):
class Meta:
Expand Down