diff options
| author | Josef Rousek <josef.rousek@gmail.com> | 2016-11-05 12:27:44 +0100 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2016-12-28 10:45:22 -0500 |
| commit | aaecf038cae61f114db396f74e06759c95f21e93 (patch) | |
| tree | 84ec007f12503ce6ccb5ae39850654c5da3e303f /django/forms | |
| parent | 6dbe56ed7855f34585884a2381fb1cec22ddc824 (diff) | |
Fixed #27370 -- Prevented Select widget from using 'required' with a non-empty first value.
Diffstat (limited to 'django/forms')
| -rw-r--r-- | django/forms/widgets.py | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/django/forms/widgets.py b/django/forms/widgets.py index dd68662d43..4f028d34ad 100644 --- a/django/forms/widgets.py +++ b/django/forms/widgets.py @@ -680,6 +680,28 @@ class Select(ChoiceWidget): context['widget']['attrs']['multiple'] = 'multiple' return context + @staticmethod + def _choice_has_empty_value(choice): + """Return True if the choice's value is empty string or None.""" + value, _ = choice + return ( + (isinstance(value, six.string_types) and not bool(value)) or + value is None + ) + + def use_required_attribute(self, initial): + """ + Don't render 'required' if the first <option> has a value, as that's + invalid HTML. + """ + use_required_attribute = super(Select, self).use_required_attribute(initial) + # 'required' is always okay for <select multiple>. + if self.allow_multiple_selected: + return use_required_attribute + + first_choice = next(iter(self.choices), None) + return use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice) + class NullBooleanSelect(Select): """ |
