gpt4 book ai didi

python - Flask WTForms SelectField 获取当前选中的项目

转载 作者:行者123 更新时间:2023-12-03 17:00:31 27 4
gpt4 key购买 nike

我在提交时难以在 Flask 应用程序的 WTForms 页面中获取当前选定的项目。 form.tableselector.data 的值在提交时始终等于 1,无论 SelectField 中的哪个项目被选中(并且所有选项都有一个唯一的 table id,从 form (1, 'table_name') 的 1 到 10,其中 1 是一个整数。

这是当前代码:

View .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

表格.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

表格 View .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 正在工作。

最佳答案

问题是我在 View 中调用了错误的参数。

见这里:How to obtain values of request variables using Python and Flask

采用:

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

关于python - Flask WTForms SelectField 获取当前选中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41428638/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com