You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask-Bootstrap中为多选下拉框设置多个默认值

How to Set Multiple Default Values for Flask-Bootstrap Multi-Select Dropdown

Got it, let's fix this step by step—you want to pre-select multiple options in your multi-select dropdown using Flask-WTF and Flask-Bootstrap. Here's the complete solution:

1. First, Ensure Your Form Field is Defined Correctly

You need to use SelectMultipleField for the days field, with clear value-display text pairs. This is critical because default values must match the value of the options, not the displayed text.

from flask_wtf import FlaskForm
from wtforms import SelectMultipleField, SubmitField
from wtforms.validators import InputRequired

class DaysForm(FlaskForm):
    # Define the multi-select field with choices (value, display text)
    days = SelectMultipleField('Select Working Days',
        choices=[
            ('sat', 'Saturday'),
            ('sun', 'Sunday'),
            ('mon', 'Monday'),
            ('tue', 'Tuesday'),
            ('wed', 'Wednesday'),
            ('thu', 'Thursday'),
            ('fri', 'Friday')
        ],
        validators=[InputRequired()]
    )
    submit = SubmitField('Save Selection')

2. Set Default Values in Your Flask View

Instead of passing a separate working_days list, set the default values directly on the form field's data attribute. Make sure the values match the choices you defined above.

from flask import Flask, render_template, request
from forms import DaysForm  # Import your form class
from flask_bootstrap import Bootstrap

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
Bootstrap(app)

@app.route("/", methods=['GET', 'POST'])
def hello():
    # Define your default selected days (match the 'value' from choices)
    default_selected_days = ['mon', 'tue', 'wed', 'fri']
    
    form = DaysForm()
    
    # Set default values only for GET requests (so POST submissions aren't overwritten)
    if request.method == 'GET':
        form.days.data = default_selected_days
    
    # Handle form submission if needed
    if form.validate_on_submit():
        selected_days = form.days.data
        # Do something with selected_days...
    
    return render_template('hello.html', form=form)

3. Update Your Template to Render the Field Correctly

Flask-Bootstrap's wtf.form_field will automatically apply the selected attribute to the default values you set. Just make sure your form points to the correct route and uses POST method:

<form class="form-group" action="{{ url_for('hello') }}" method="post">
    {{ form.csrf_token }}
    <!-- This will render the multi-select with pre-selected options -->
    {{ wtf.form_field(form.days) }}
    {{ wtf.form_field(form.submit) }}
</form>

Key Notes to Remember

  • Match Values, Not Display Text: Your default list must use the value part of your form choices (e.g., 'mon' instead of 'Monday').
  • Only Set Defaults on GET: If you set form.days.data for all request methods, you'll overwrite user-submitted values from POST requests.
  • Multi-select Behavior: The rendered <select> tag will have the multiple attribute, so users can select multiple options (hold Ctrl/Cmd to select multiple).

When you run this, the generated HTML will include the selected attribute on your default days, like this:

<select class="form-control" id="days" multiple name="days" required>
    <option value="sat">Saturday</option>
    <option value="sun">Sunday</option>
    <option value="mon" selected>Monday</option>
    <option value="tue" selected>Tuesday</option>
    <option value="wed" selected>Wednesday</option>
    <option value="thu">Thursday</option>
    <option value="fri" selected>Friday</option>
</select>

内容的提问来源于stack exchange,提问作者user9657909

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:19:48