Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 263
Azurelle Avatar asked Jul 08 '16 02:07

Azurelle


1 Answers

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()]
like image 146
Matt Healy Avatar answered Oct 18 '22 09:10

Matt Healy