简体   繁体   English

使用Flask和WTForms从数据库查询的动态单选按钮

[英]Dynamic radio buttons from database query using Flask and WTForms

I have experience with PHP but im new to Flask and Python and I need help with a simple thing. 我有使用PHP的经验,但我是Flask和Python的新手,我需要一些简单的帮助。

I have a database table and I need each entry in a radio button. 我有一个数据库表,我需要一个单选按钮中的每个条目。 I need to use WTForms but I can't do it. 我需要使用WTForms,但我不能这样做。 The id should be the value and the botname should be the label. id应该是值,botname应该是标签。

This is my table: 这是我的表:

class Probot(db.Model):
    __tablename__ = "probot"    
    id = db.Column(db.Integer, primary_key=True)
    botname = db.Column(db.String(20), unique=True, index=True)
    is_available = db.Column(db.Boolean, nullable=False, default=True)
    battery = db.Column(db.Integer)
    registered_on = db.Column(db.DateTime,default=datetime.datetime.utcnow())

I use the query: Probot.query.all() but how do I use the results in the choices atribute of the RadiofField on the form? 我使用查询:Probot.query.all()但是如何在表单上的RadiofField的选择属性中使用结果?

class SimpleForm(Form):
    example = RadioField('Label', choices=[])

I have tried many ways but I always get errors I would appreciate some help. 我尝试了很多方法,但我总是会遇到错误,我会感激一些帮助。 Thank You. 谢谢。

Since you are setting the choices dynamically, don't declare them when defining your form. 由于您是动态设置选项,因此在定义表单时不要声明它们。 Instead, in your view function, you need to instantiate the form like this (the below is untested): 相反,在您的视图函数中,您需要像这样实例化表单(以下是未经测试的):

form = SimpleForm()

form.example.choices = [(probot.id, probot.botname) for probot in Probot.query.all()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM