Flask,SQLAlchemy:如何使用wtforms.ext.sqlalchemy.fields.QuerySelectField进行下拉

时间:2018-11-23 21:03:33

标签: python flask sqlalchemy flask-sqlalchemy

我是Flask / SQLAlchemy的新手。我有一个包含两个表的数据库:Family和Chart。家庭表具有两列:id和familyname。图表表有几列,包括行业。我能够显示“家庭/家庭”字段的下拉列表,但无法显示“图表/行业”字段的下拉列表。这是我的代码,非常感谢您的帮助。

forms.py

from flask import request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.validators import ValidationError, DataRequired, Length
from app.models import Family, Chart

def family_query():
    return Family.query.order_by('familyname asc').all()
def industry_query():
    return Chart.query(Chart.industry.distinct()).all()
class FamilyForm(FlaskForm):
    optsFamily = QuerySelectField(query_factory=family_query,allow_blank=True, get_label='familyname',  blank_text="Click to select")
    optsIndustry = QuerySelectField(query_factory=industry_query,allow_blank=True, get_label='industry',  blank_text="Click to select")

routes.py

from flask import render_template, flash, redirect, url_for, request, g,current_app
from app import db
from app.main.forms import FamilyForm
from app.models import Family, Chart
from app.main import bp

@bp.route('/', methods=['GET', 'POST'])
def index():
    form = FamilyForm()
    return render_template('index.html', form = form )

HTML

    {{ form.csrf_token }}
    {{ form.optsFamily }}
     <ul>
      {% for error in form.optsFamily.errors %}
      <li style="color:red;">{{ error }}</li>
      {% endfor %}
   </ul>
    {{ form.optsIndustry }}  
    <ul>
      {% for error in form.optsIndustry.errors %}
      <li style="color:red;">{{ error }}</li>
      {% endfor %}
   </ul>

1 个答案:

答案 0 :(得分:0)

明白了。我将查询更新为以下内容:

def industry_query():
    return Chart.query.order_by('industry asc').distinct('industry').all()