具有WTF和Flask的Bootstrap下拉菜单

问题描述

我是创建Flask / WTF / Jinja2(使用Bootstrap)网站的业余爱好者,但我尚未实现下拉按钮。不幸的是,我真的在Bootstrap / Jinja2元素中苦苦挣扎(我可以将数据保存到jinja2中,但无法正确渲染任何内容)。如果有帮助的话,我是来自YouTube上Flask上的Corey Schafer学校的人。

这是我的WTF类声明:

class SegmentForm(FlaskForm):
     segmentID = SelectField(label='Choose a Segment',coerce=int,validators=[Inputrequired])

这是我的路线(烧瓶)声明:

@decks.route('/decks/segments',methods=['GET'])
@login_required
def segments():
    form = SegmentForm()
    pathname = os.path.abspath(os.path.dirname(__file__))

    df = pd.read_csv(pathname + '/upload_data/segment_summary.csv',index_col=None)
    form.segmentID.choices = df.seg_name

我正在努力解决的问题是要弄清Bootstrap / Jinja2:

    <div class="dropdown">
        <button class="btn btn-primary dropdown-toggle" type="button" id={{form.segmentID.label}}>
            {{ form.segmentID.label }}
        </button>
        <div class="dropdown-menu" aria-labelledby={{form.segmentID.label}}>
                {% for segment in form.segmentID.choices %}
                  <option value="{{ segment }}">{{ segment }}</option>
                {% endfor %}
        </div>
    </div>

解决方法

form.py:

from flask_wtf import FlaskForm
from wtforms import SubmitField,SelectField,SelectMultipleField,widgets
from wtforms.validators import DataRequired,NumberRange,InputRequired,Length
 
class MultiCheckboxField(SelectMultipleField):
     widget = widgets.ListWidget(prefix_label=False)
     option_widget = widgets.CheckboxInput()

class FindSegmentForm(FlaskForm):
     submit = SubmitField('Identify Segment for Deck')
     clear = SubmitField('Reset to Blanks')
     cards = MultiCheckboxField('Select Cards for Deck',coerce=int)

从routes.py:

card_list = list(zip(df.card_id.to_list(),df.card_names.to_list()))
form.cards.choices = card_list

从display.html:

{% for cards in form.cards %}
    <div class="form-check">
        {{ cards(class="form-check-input") }}
        {{ cards.label(class="form-check-label") }}
    </div>
{% endfor %}

感谢ectrimble的原始解决方案。 (https://gist.github.com/ectrimble20/468156763a1389a913089782ab0f272e