title: Flask, SQLAlchemy: how to use wtforms.ext.sqlalchemy.fields.QuerySelectField for dropdowns
body: <p>I'm new to Flask/SQLAlchemy.  I have a database with two tables:  Family and Chart.  The Family table has two columns: id and familyname.  The Chart table has several columns including industry.  I was able to display the dropdown for Family/family field, but not the dropdown for Chart/industry field.  Here is my code and would appreciate the help.</p>
  
  <p>forms.py</p>
  
  <pre><code>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")
  </code></pre>
  
  <p>routes.py</p>
  
  <pre><code>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 )
  </code></pre>
  
  <p>HTML</p>
  
  <pre><code>    {{ form.csrf_token }}
      {{ form.optsFamily }}
       &lt;ul&gt;
        {% for error in form.optsFamily.errors %}
        &lt;li style="color:red;"&gt;{{ error }}&lt;/li&gt;
        {% endfor %}
     &lt;/ul&gt;
      {{ form.optsIndustry }}  
      &lt;ul&gt;
        {% for error in form.optsIndustry.errors %}
        &lt;li style="color:red;"&gt;{{ error }}&lt;/li&gt;
        {% endfor %}
     &lt;/ul&gt;
  </code></pre>