[英]Populate a WTForms SelectField with an SQL query
我想使用此查询返回的行填充 WTForms SelectField:
cur.execute("SELECT length FROM skipakke_alpin_ski WHERE stock > 0")
该查询返回包含不同类型滑雪板的滑雪板长度的行。 cur.fetchall()
返回以下元组:
[(70,), (75,), (82,), (88,), (105,), (115,), (125,), (132,), (140,), (150,), (160,), (170,)]
我将如何将这些数字添加到SelectField
,以便每个滑雪板长度都是自己可选择的选择? 如果我手动完成此操作,我会执行以下操作:
ski_size = SelectField('Ski size', choices=['70', '70', '75', '75'])
... 等等所有不同的长度。
在我使用过的项目之一中,如下所示:
楷模
class PropertyType(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), nullable=False)
def __repr__(self):
return str(self.id)
并在表格中
from wtforms.ext.sqlalchemy.fields import QuerySelectField
class PropertyEditor(Form):
property_type = QuerySelectField(
'Property Type',
query_factory=lambda: models.PropertyType.query,
allow_blank=False
)
//Other remaining fields
希望这可以帮助。
解决方案可能类似于下面的代码。
假设你有两个文件: routes.py
和views.py
在routes.py
文件中你把这个
from flask_wtf import FlaskForm
from wtforms import SelectField
# Here we have class to render ski
class SkiForm(FlaskForm):
ski = SelectField('Ski size')
在views.py
文件中你把这个
# Import your SkiForm class from `routes.py` file
from routes import SkiForm
# Here you define `cur`
cur = ...
# Now let's define a method to return rendered page with SkiForm
def show_ski_to_user():
# List of skies
cur.execute("SELECT length FROM skipakke_alpin_ski WHERE stock > 0")
skies = cur.fetchall()
# create form instance
form = SkiForm()
# Now add ski length to the options of select field
# it must be list with options with (key, value) data
form.ski.choices = [(ski, ski) for ski in skies]
# If you want to use id or other data as `key` you can change it in list generator
if form.validate():
# your code goes here
return render_template('any_file.html', form=form)
请记住,默认key
是 unicode。 如果你想在 SkiForm 类中使用 int 或其他数据类型使用coerce
参数,像这样
class SkiForm(FlaskForm):
ski = SelectField('Ski size', coerce=int)
我通过执行以下操作设法解决了这个问题:
def fetch_available_items(table_name, column):
with sqlite3.connect('database.db') as con:
cur = con.cursor()
cur.execute("SELECT length FROM skipakke_alpin_ski WHERE stock > 0")
return cur.fetchall()
class SkipakkeForm(Form):
alpin_ski = SelectField('Select your ski size', choices=[])
@app.route('/skipakke')
def skipakke():
form = SkipakkeForm
# Clear the SelectField on page load
form.alpin_ski.choices = []
for row in fetch_available_items('skipakke_alpin_ski', 'length'):
stock = str(row[0])
form.alpin_ski.choices += [(stock, stock + ' cm')]
解决方案:
我遇到了非常相似的问题,这是我的解决方法
class SkiForm(FlaskForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
cur.execute("SELECT length FROM skipakke_alpin_ski WHERE stock > 0")
skies = cur.fetchall()
self.ski_size.choices = [
(ski , ski) for ski in skies
]
ski_size = SelectField("Ski size")
解释:
我们修改了原来的FlaskForm
,让它在每次创建时都执行数据库查询。
因此, SkiForm
字段数据选择始终保持最新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.