mirror of
https://github.com/django/django.git
synced 2025-08-03 10:34:04 +00:00
Fixed #27039 -- Fixed empty data fallback to model field default in model forms.
This commit is contained in:
parent
426bca002c
commit
4bc6b93994
6 changed files with 69 additions and 2 deletions
|
@ -565,6 +565,42 @@ class ModelFormBaseTest(TestCase):
|
|||
self.assertEqual(list(OrderFields2.base_fields),
|
||||
['slug', 'name'])
|
||||
|
||||
def test_default_populated_on_optional_field(self):
|
||||
class PubForm(forms.ModelForm):
|
||||
mode = forms.CharField(max_length=255, required=False)
|
||||
|
||||
class Meta:
|
||||
model = PublicationDefaults
|
||||
fields = ('mode',)
|
||||
|
||||
# Empty data uses the model field default.
|
||||
mf1 = PubForm({})
|
||||
self.assertEqual(mf1.errors, {})
|
||||
m1 = mf1.save(commit=False)
|
||||
self.assertEqual(m1.mode, 'di')
|
||||
self.assertEqual(m1._meta.get_field('mode').get_default(), 'di')
|
||||
|
||||
# Blank data doesn't use the model field default.
|
||||
mf2 = PubForm({'mode': ''})
|
||||
self.assertEqual(mf2.errors, {})
|
||||
m2 = mf2.save(commit=False)
|
||||
self.assertEqual(m2.mode, '')
|
||||
|
||||
def test_default_not_populated_on_optional_checkbox_input(self):
|
||||
class PubForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = PublicationDefaults
|
||||
fields = ('active',)
|
||||
|
||||
# Empty data doesn't use the model default because CheckboxInput
|
||||
# doesn't have a value in HTML form submission.
|
||||
mf1 = PubForm({})
|
||||
self.assertEqual(mf1.errors, {})
|
||||
m1 = mf1.save(commit=False)
|
||||
self.assertIs(m1.active, False)
|
||||
self.assertIsInstance(mf1.fields['active'].widget, forms.CheckboxInput)
|
||||
self.assertIs(m1._meta.get_field('active').get_default(), True)
|
||||
|
||||
|
||||
class FieldOverridesByFormMetaForm(forms.ModelForm):
|
||||
class Meta:
|
||||
|
@ -774,7 +810,10 @@ class UniqueTest(TestCase):
|
|||
title = 'Boss'
|
||||
isbn = '12345'
|
||||
DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
|
||||
form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'isbn': isbn})
|
||||
form = DerivedBookForm({
|
||||
'title': 'Other', 'author': self.writer.pk, 'isbn': isbn,
|
||||
'suffix1': '1', 'suffix2': '2',
|
||||
})
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertEqual(len(form.errors), 1)
|
||||
self.assertEqual(form.errors['isbn'], ['Derived book with this Isbn already exists.'])
|
||||
|
@ -2491,7 +2530,7 @@ class OtherModelFormTests(TestCase):
|
|||
class PublicationDefaultsForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = PublicationDefaults
|
||||
fields = '__all__'
|
||||
fields = ('title', 'date_published', 'mode', 'category')
|
||||
|
||||
self.maxDiff = 2000
|
||||
form = PublicationDefaultsForm()
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue