1
0
mirror of https://github.com/django/django.git synced 2025-11-07 07:15:35 +00:00

Fixed #27370 -- Prevented Select widget from using 'required' with a non-empty first value.

This commit is contained in:
Josef Rousek
2016-11-05 12:27:44 +01:00
committed by Tim Graham
parent 6dbe56ed78
commit aaecf038ca
7 changed files with 70 additions and 27 deletions

View File

@@ -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):
"""