SQL Alchemy / Flask / WTF Forms为queryselectfield设置默认值

时间:2017-07-05 08:47:37

标签: python flask sqlalchemy wtforms

我想为queryselectfield设置默认值。我的代码如下所示:

模板:

{% import "bootstrap/utils.html" as utils %}
{% import "bootstrap/wtf.html" as wtf %}
{% extends "base.html" %}
{% block title %}Request{% endblock %}
{% block body %}
<div class="content-section">
...
{{ form.country(class_="selectformfield") }
...

路线:

@requests.route('/request/add', methods=['GET', 'POST'])
@login_required
def add_request():

check_admin()

add_request = True

form = RequestForm()
if form.validate_on_submit():
    ...
    Country = form.hostname.data
    ...

    request = Request(...country=country, ...)

    try:
        # add request to the database
        db.session.add(request)
        db.session.commit()
        flash('You have successfully added a new request.')
    except:
        # in case request name already exists
        flash('Error: request already exists.')

    # redirect to the request page
    return redirect(url_for('requests.show_request', id=request.id))

# load request template
return render_template('requests/add_request.html', add_request=add_request,
                       form=form, title='Add new Request')

形式:

class RequestForm(FlaskForm):
...
country = QuerySelectField(query_factory=lambda: Country.query.all(), get_label="name")
...

我已经尝试过这样,但它没有用。

default_country = query_factory=lambda: Country.query.filter(Country.id == '1')
country = QuerySelectField(query_factory=lambda: Country.query.all(), get_label="name", default=default_country)

SQLAlchemy/WTForms: set default selected value for QuerySelectField 我也已经在这里阅读了这篇文章并提出了一个相似的问题,但解决方案对我来说并不适用。 annyone可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

尝试一下:

default=lambda: Country.query.filter(Country.id == '1').one_or_none())

此处是您的字段定义的完整代码:

country = QuerySelectField(query_factory=lambda: Country.query.all(), get_label="name", default=lambda: Country.query.filter(Country.id == '1').one_or_none())