Dynamic radio buttons from database query using Flask and WTForms
Asked Answered
E

1

9

I have experience with PHP but im new to Flask and Python and I need help with a simple thing.

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. The id should be the value and the botname should be the label.

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?

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

I have tried many ways but I always get errors I would appreciate some help. Thank You.

Expertism answered 8/7, 2016 at 2:17 Comment(0)
C
6

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()]
Cheerly answered 8/7, 2016 at 7:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.