Flask – QuerySelectField Tutorial

When you’re reading on this article, most probably you’re looking solution for how QuerySelectField to pre-populate the value. Example, when edit a record, you need to populate the previously selected record.

Form

class CategoryForm(FlaskForm):
    name_en = StringField('Category (en)',[
        validators.Required(),
        validators.Length(min=6, max=255)
    ])
    parent = QuerySelectField('Parent', 
        query_factory=categories, allow_blank=True, 
        get_label='name_en', get_pk=lambda a: a.id,
        blank_text=u'Select a categories...')

    submit = SubmitField('Save')

 

Solution

The solution is quite simple,  if the QuerySelectField is named as parent, when you’re doing editing just need to pass the selected option as an object. Example, form = CategoryForm(parent=category).  Category = object to passed

 

@login_required
@app.route('/category/edit/<id>', methods = ['GET','POST'])
def category_edit(id=None):
    if id is not None:
      category = Category.query.get(id)
    
    form = CategoryForm(parent=category)
    error = None
    .....
    return render_template('category/edit.html', error=error, form=form)   

 

 

 

Gist

https://gist.github.com/loongest/0b2131b75dbde951dc85aef739fe9c93

 

Flask – QuerySelectField Tutorial

2 thoughts on “Flask – QuerySelectField Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.