使用sqlAlchemy查询动态填充WTForm SelectField

时间:2018-10-03 21:02:55

标签: python postgresql flask sqlalchemy wtforms

我正在尝试使用来自postgreSQL数据库中一列的数据动态填充下拉菜单中的选项。当我尝试加载表单时,我得到:TypeError:'NoneType'对象不可迭代。任何帮助将不胜感激。

  File "/usr/lib/python2.7/site-packages/wtforms/widgets/core.py", line 323, in __call__
    for val, label, selected in field.iter_choices():
  File "/usr/lib/python2.7/site-packages/wtforms/fields/core.py", line 454, in iter_choices
    for value, label in self.choices:
TypeError: 'NoneType' object is not iterable

Model.py

class ReqCriterion(Base):
    __tablename__ = 'req_criteria'

    criteria_id = Column(Integer, primary_key=True, server_default=text("nextval('req_criteria_criteria_id_seq'::regclass)"))
    req_id = Column(Integer, nullable=False)
    req_name = Column(Text)
    coi_id = Column(Integer, nullable=False)
    coi_name = Column(Text, nullable=False)
    criteria = Column(Text)

    def __init__(self, criteria, req_name, coi_id, coi_name, req_id):
        self.criteria = criteria
        self.req_id = req_id
        self.req_name = req_name
        self.coi_id = coi_id
        self.coi_name = coi_name

forms.py

class NewProjForm(Form):
    pj_name = StringField('Project Name', validators=[InputRequired(), Length(min=1, max=1000)])
    pj_desc = TextAreaField('Project Description', validators=[InputRequired(), Length(min=1, max=3000)])
    coi_name = SelectField('COI:', validators=[InputRequired()])
    pj_poc_first = StringField('POC First Name', validators=[InputRequired(), Length(min=1, max=500)])
    pj_poc_last = StringField('POC Last Name', validators=[InputRequired(), Length(min=1, max=500)])

app.py

@app.route('/addProjForm', methods=['GET','POST'])
def addProjForm():
        newProj = NewProjForm(request.form)
        newProj.coi_name.choices = db.session.query(ReqCriterion).filter(coi_name)
        if request.method == 'POST' and newProj.validate():
            addProj = Project(request.form['pj_name'], request.form['pj_desc'], request.form['coi_name'], request.form['pj_poc_first'], request.form['pj_poc_last'])
            db.session.add(addProj)
            db.session.commit()
            return redirect(url_for('project_conf', addProj=addProj))

1 个答案:

答案 0 :(得分:1)

我应该一直使用QuerySelectField和lambda,并在模型中添加了 repr 。这对我有用:

Forms.py

coi_name = QuerySelectField(label='COI', query_factory=lambda: db.session.query(Coi).filter_by(active=1), get_pk=lambda coi_id: coi_id, get_label=lambda coi_name: coi_name, allow_blank=True)

Models.py

def __repr__(self):
        return '{}'.format(self.coi_name)