6

What is the simplest way to assign 'disabled' html attribute to one of the options in SelectField in WTForms?

This is my previous code

<select class="form-control" name="division" data-error="Required!" required>
     <option value="default" disabled selected>Select something</option>
     <option value="option1">Option 1</option>
     <option value="option2">Option 2</option>
 </select>

As you can see I would like to set 'disabled' only to first option.

My code for this task is:

next(form.division.__iter__())(**{'disabled':'true'})

And using print function in console I can see the proper output:

<option disabled="true" selected value="default">Select something</option>

The line is working, but somehow this output is not passed to the template. Instead this is what's passed:

<option selected value="default">Select something</option>

Please someone make it clear.

4 Answers 4

6

If you simply just want a disabled and selected option as the first option of your select, I found this to be simpler than extending the SelectField class:

Just loop over the option and check for first loop iteration

<select name="my_select" id="my_select">
    {% for option in form.my_select %}
        {% if loop.first %}
            <option value="" disabled selected>select something</option>
        {% endif %}
        {{ option }}
    {% endfor %}
</select>
1
  • This should be marked as the solution, as the "select something" placeholder disabled option is an issue that concerns presentation only, and its solution should reside in the presentation layer (jinja template logic)
    – sscarduzio
    Aug 8, 2022 at 9:55
3

Here's a custom wtforms widget which makes use of the SelectField's Options iterator.

from markupsafe import Markup
from wtforms.widgets.core import html_params


class CustomSelect:
    """
    Renders a select field allowing custom attributes for options.
    Expects the field to be an iterable object of Option fields.
    The render function accepts a dictionary of option ids ("{field_id}-{option_index}")
    which contain a dictionary of attributes to be passed to the option.

    Example:
    form.customselect(option_attr={"customselect-0": {"disabled": ""} })
    """

    def __init__(self, multiple=False):
        self.multiple = multiple

    def __call__(self, field, option_attr=None, **kwargs):
        if option_attr is None:
            option_attr = {}
        kwargs.setdefault("id", field.id)
        if self.multiple:
            kwargs["multiple"] = True
        if "required" not in kwargs and "required" in getattr(field, "flags", []):
            kwargs["required"] = True
        html = ["<select %s>" % html_params(name=field.name, **kwargs)]
        for option in field:
            attr = option_attr.get(option.id, {})
            html.append(option(**attr))
        html.append("</select>")
        return Markup("".join(html))

When declaring the field, pass an instance of CustomSelect as the widget parameter.

division = SelectField(
    "Division",
    choices=[("default", "Select something"), ("option1", "Option 1"), ("option2", "Option 2")],
    validators=[InputRequired()],
    widget=CustomSelect(),
    default="default",
)

And to pass attributes when rendering

form.division(option_attr={"division-0": {"disabled": ""} }, class="form-control")
0
2

When you disable the field the values are no longer passed. What you might want to do is pass the variable by using read only instead of disabled. Here's how do to it with jquery :

$('#id_of_option').prop('readonly', true);

Also what I've done is set choices in Wtforms where

choices = [('', 'please select an option'), ('1', 'option 1'),  ('2', 'option 2')]

and this way a user has to select a value.

3
  • I know there's JS workaround, my code for that is: document.getElementById('division').firstChild.setAttribute("disabled", "true"); , but i was wondering if there's some better solution for that. thanks anyway
    – MacZel
    Jun 6, 2017 at 0:12
  • Why not set it to read-only? The user cannot use that option and the value gets passed to the form. Also, if you set your choices utilizing Wtforms as I showed above then the user cannot select the first option. That's what I've been doing and it works well. Good luck and curious as to what you find.
    – timmyjl12
    Jun 6, 2017 at 1:21
  • Well I had some misconceptions on read-only, but it does the job. Last one: How do you set WTForms to create 'id' attribute for every option field? For every other field it is set automatically, but somehow for option field it is not working for me.
    – MacZel
    Jun 6, 2017 at 4:43
0

This worked for me.

<select id="{{ form.my_select.id }}" name = "{{ form.my_select.name }}">
    {% for option in form.my_select %}
        {% if loop.first %}
            {{ option(disabled="") }}
        {% else %}
            {{ option }}
        {% endif %}
    {% endfor %}
</select>

The HTML 'disabled' attribute is a boolean one and in regular HTML, it does not need to be assigned to "". Without the equal sign, I got some positional argument errors.

If you want to disable other options (say, 4th and 5th option in addition to the first one), you can do this:

<select id="{{ form.my_select.id }}" name = "{{ form.my_select.name }}">
    {% for option in form.my_select %}
        {% if loop.first %}
            {{ option(disabled="") }}
        {% elif loop.index == 4 or loop.index == 5 %}
            {{ option(disabled="") }}
        {% else %}
            {{ option }}
        {% endif %}
    {% endfor %}
</select>

Note that loop.index is 1-based.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.