diff --git a/django/forms/forms.py b/django/forms/forms.py index 19d5778468a..86f9399001c 100644 --- a/django/forms/forms.py +++ b/django/forms/forms.py @@ -99,6 +99,12 @@ class BaseForm: if use_required_attribute is not None: self.use_required_attribute = use_required_attribute + if self.empty_permitted and self.use_required_attribute: + raise ValueError( + 'The empty_permitted and use_required_attribute arguments may ' + 'not both be True.' + ) + # Initialize form renderer. Use a global default if not specified # either as an argument or as self.default_renderer. if renderer is None: diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py index 1f883e1a285..b326468d698 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -2682,7 +2682,7 @@ Good luck picking a username that doesn't already exist.

self.assertEqual(form.cleaned_data, {}) # Now let's show what happens when empty_permitted=True and the form is empty. - form = SongForm(data, empty_permitted=True) + form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) self.assertEqual(form.errors, {}) self.assertEqual(form.cleaned_data, {}) @@ -2699,7 +2699,7 @@ Good luck picking a username that doesn't already exist.

# make sure that when checking for empty_permitted that None is treated # accordingly. data = {'artist': None, 'song': ''} - form = SongForm(data, empty_permitted=True) + form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) # However, we *really* need to be sure we are checking for None as any data in @@ -2709,9 +2709,17 @@ Good luck picking a username that doesn't already exist.

qty = IntegerField() data = {'amount': '0.0', 'qty': ''} - form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True) + form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) + def test_empty_permitted_and_use_required_attribute(self): + msg = ( + 'The empty_permitted and use_required_attribute arguments may not ' + 'both be True.' + ) + with self.assertRaisesMessage(ValueError, msg): + Person(empty_permitted=True, use_required_attribute=True) + def test_extracting_hidden_and_visible(self): class SongForm(Form): token = CharField(widget=HiddenInput)