Opened 6 years ago

Last modified 2 years ago

#27370 closed Cleanup/optimization

Django's Select widget adds a required="required" attribute, even if created with empty_label=True — at Initial Version

Reported by: alexpirine Owned by: nobody
Component: Forms Version: dev
Severity: Normal Keywords: HTML, Select, wdiget, ModelChoiceField
Cc: Aurélien Pardon Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I didn't think it was wrong in HTML, but the W3C validator says so, and after reading this discussions, it seems to be right:

https://github.com/validator/validator/issues/47

This is how I could explain it:

If a form field is required and has the empty_label=True argument, the generated <select> will have a required="required" attribute. This doesn't make sense since the first item will be selected anyways, and there is no way for the user to unselect a value.

So, the required="required" attribute is useless.

Example:

class TestForm(forms.Form):
    some_field = forms.ModelChoiceField(queryset=SomeModel.objects.all(), empty_label=None)

results in:

<select id="id_some_field" name="some_field" required>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<!-- ... -->
</select>

You can check the following code using the W3C validation service:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Validation test</title>
</head>
<body>
  <select id="id_some_field" name="some_field" required>
    <option value="1">Value 1</option>
    <option value="2">Value 2</option>
    <option value="3">Value 3</option>
    <!-- ... -->
  </select>
</body>
</html>

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top