簡體   English   中英

Flask WTForms SelectField獲取當前選中的項目

[英]Flask WTForms SelectField get currently selected item

我在提交時難以在Flask應用程序的WTForms頁面中獲取當前選擇的項目。 無論選擇了SelectField中的哪個項目,form.tableselector.data值在提交時始終等於1(並且所有選擇都具有從1到10的唯一表ID,格式為(1,'table_name'),其中1為一個整數。

這是當前代碼:

views.py

from flask import session

def view(self):
    form = Tableset(request.form)
    if request.method == 'POST' and form.validate():
        #form.tableselector.data always returns 1 no matter which item is selected?
        session['table_id'] = form.tableselector.data

form.py

class MyBaseForm(Form):
    #see https://wtforms.readthedocs.io/en/latest/csrf.html
    class Meta:
        csrf = True
        csrf_class = SessionCSRF
        csrf_secret = app.config.get('SECRET_KEY')

        @property
        def csrf_context(self):
            return session

class Tableset(MyBaseForm):
    tableselector = SelectField(label = 'Table', choices = [], coerce=int, id='select_table')
    submit = SubmitField('Submit')

    def validate(self):
        if len(self.tableselector.choices) == 0:
            return False
        return True

tableview.html

<form role="form" action="{{ url_for('app.table_view') }}" method="post">
    {{ form.csrf_token }}
    <div class="form-group">
    {{ form.tableselector.label }} 
    {{ form.tableselector }}
    </div>

我注意到在調試表單時wtf Meta對象的csrf屬性等於True,所以我知道CSRF可以正常工作。

問題是我在視圖中調用了錯誤的參數。

參見此處: 如何使用Python和Flask獲取請求變量的值

采用:

if request.method == 'POST' and form.validate():
    session['table_id'] = request.form.get('tableselector')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM