J. Raji
J. Raji

Reputation: 143

Pre-populate (Query) SelectField - WTForms?

I'm trying pre-populate a Select Field using WTForms. I want to pre-populate the Select Field (value and label) using data from a database.

Database:

+----+----------+-------------------------------------+--------+
| id | category | description                         | status |
+----+----------+-------------------------------------+--------+
|  1 | Cinema   | About movies                        |      1 |
|  2 | Play     | About music.                        |      0 |
|  3 | News     | Breaking news                       |      1 |
+----+----------+-------------------------------------+--------+

I want a QuerySelectField equivalent to this:

class MyForm(Form):
    category = SelectField(u'Category', choices=[('1', 'Cinema'), ('3','News')])

I've done this so far:

def getCategories():
    return Category.query.filter_by(status=1).all()

class MyForm(Form):
    category = QuerySelectField(u'Category',
            [validators.Required()],
            query_factory = getCategories
            )

The labels are rendered like this:

<select class="form-control" id="category" name="category">
<option value="1">&lt;models.Category object at 0x105064910&gt;</option>
<option value="3">&lt;models.Category object at 0x105064d50&gt;</option>
</select>

Upvotes: 1

Views: 3198

Answers (2)

Espoir Murhabazi
Espoir Murhabazi

Reputation: 6396

i think you can try this code

categorie=QuerySelectField(query_factory=lambda:Category.query.filter_by(status=1).all(),get_label="name")

in your form you can find more this awesome turorial they use it simpe crud app with forms

Upvotes: 4

MrLeeh
MrLeeh

Reputation: 5589

You're doing alright. The QuerySelectField uses the string representation of your Model object for displaying. Just add a __str__ function to your Category model that returns the category name.

def __str__(self):
    return self.name

Upvotes: 3

Related Questions