django-countries
django-countries copied to clipboard
COUNTRIES_FIRST_BREAK prevents the form widget from being required?
It seems that if I set COUNTRIES_FIRST_BREAK
, the widget doesn't render the required
attribute?
with these settings:
COUNTRIES_FIRST = ["US", "RU", ]
COUNTRIES_FIRST_REPEAT = True
COUNTRIES_FIRST_SORT = False
COUNTRIES_FIRST_BREAK = "-----"
If I remove COUNTRIES_FIRST_BREAK from settings it works as expected (required=""
in the select tag)
With
django-countries==5.5 Django==2.2.6
Interesting, this is because of this, in django.forms.widgets.Select
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().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)
( https://github.com/django/django/blob/48df40262bb13ff923dcbafc2bc70af12fe9db47/django/forms/widgets.py#L691-L702 )
See https://code.djangoproject.com/ticket/27370 - "The first child option element of a select element with a required attribute, and without a multiple attribute, and without a size attribute whose value is greater than 1, must have either an empty value attribute, or must have no text content."
It seems like the validator is requiring the first element to be empty, though from my reading the actual HTML spec doesn't require that the placeholder is the first <option>
https://www.w3.org/TR/html52/sec-forms.html#placeholder-label-option
Anyway, assuming that's not something we want to work-around, maybe the solution is documentation that setting COUNTRIES_FIRST_BREAK will make the widget not render required
?