forms: only display selected option for readonly select widgets (#40520)

This commit is contained in:
Frédéric Péters 2020-06-29 20:53:50 +02:00
parent bf52ee1ac7
commit eef03c0a56
3 changed files with 19 additions and 2 deletions

View File

@ -464,6 +464,20 @@ def test_select_widget():
('peach', 'Peach', 'peach', {'disabled': True})])
assert not widget.has_valid_options()
# test readonly only includes the selected value
req.form = {}
widget = SingleSelectHintWidget('test',
options=[
('apple', 'Apple', 'apple'),
('pear', 'Pear', 'pear'),
('peach', 'Peach', 'peach')])
widget.readonly = 'readonly'
widget.attrs['readonly'] = 'readonly'
assert 'apple' in str(widget.render()) and 'pear' in str(widget.render())
widget.set_value('pear')
assert 'apple' not in str(widget.render()) and 'pear' in str(widget.render())
assert 'readonly="readonly"' not in str(widget.render())
def test_select_or_other_widget():
widget = SingleSelectWidgetWithOther('test',

View File

@ -1772,6 +1772,7 @@ class CheckboxesTableWidget(TableWidget):
class SingleSelectHintWidget(SingleSelectWidget):
template_name = 'qommon/forms/widgets/select.html'
readonly = None
def __init__(self, name, value=None, **kwargs):
self.options_with_attributes = kwargs.pop('options_with_attributes', None)
@ -1794,13 +1795,15 @@ class SingleSelectHintWidget(SingleSelectWidget):
if options[0][0] is None:
options = self.options[1:]
tags = []
for option in options:
object, description, key = option[:3]
html_attrs = {}
html_attrs['value'] = key
if self.is_selected(object):
html_attrs['selected'] = 'selected'
elif self.readonly and self.value:
# if readonly only include the selected option
continue
if self.options_with_attributes and option[-1].get('disabled'):
html_attrs['disabled'] = 'disabled'
if description is None:

View File

@ -3,7 +3,7 @@
<select id="form_{{widget.name}}" name="{{widget.name}}"
{% if widget.select2 %}data-autocomplete="true"{% endif %}
{% if widget.required %}data-required="true"{% endif %}
{% for attr in widget.attrs.items %}{{attr.0}}="{{attr.1}}"{% endfor %}>
{% for attr in widget.attrs.items %}{% if attr.0 != 'readonly' %}{{attr.0}}="{{attr.1}}"{% endif %}{% endfor %}>
{% if not widget.separate_hint and widget.hint %}
<option value="" data-hint="{{ widget.hint }}">{% if not widget.select2 %}{{ widget.hint }}{% endif %}</option>
{% endif %}