使QuerySelectField选定的数据对象成为文字值

时间:2018-12-26 00:32:43

标签: python flask sqlalchemy

我正在创建应用程序的一部分,管理员可以在其中注册用户。我有一个注册表单,其中表单的元素之一是QuuerySelectField,该属性从db获取可以链接用户的位置列表。我能够显示带有正确信息的QuerySelectField,但是提交表单后,我会收到“ sqlalchemy.exc.ArgumentError:对象“ Site”作为SQL文字值不合法”错误。尝试在表单网站模型中查询数据库以在QuerySelectField中查找所选选项的名称时,会出现此错误,以便随后可以将特定站点的ID存储在变量中以备将来使用。

我不确定如何使对象成为sqlalchemy可以读取的文字值。我尝试将其包装在str()中,但没有做任何事情。顺便说一下,我是菜鸟,所以我仍在尝试掌握烧瓶的某些元素。

这是我要完成的表格

def site():
    return Sites.query.all()

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), 
Length(min=2, max=20)])
    email = StringField('Email', validators=

[DataRequired(), Email()])
        password = PasswordField('Password', validators=[DataRequired()])
        confirm_pass = PasswordField('Confirm Password', validators= 
   [DataRequired(), EqualTo('password')])
        admin_status = BooleanField('Check for Admin Status')
        sitechoices = QuerySelectField(query_factory=site, allow_blank=False, 
   get_label='sitename')

这是我的路线中的路线信息。py

@app.route('/register', methods=['POST', 'GET'])
@login_required
def register():
    forms = RegistrationForm()
    if forms.validate_on_submit():
        hashed_pw = bcrypt.generate_password_hash(forms.password.data).decode('utf-8')
        siteid = Sites.query.filter_by(sitename=forms.sitechoices.data).first().id
        user = User(site = forms.sitechoices.data, username = forms.username.data, email = forms.email.data, 
        password = hashed_pw, adminstatus= forms.admin_status.data, sitelink=siteid)
        db.create_all()
        db.session.add(user)
        db.session.commit()
        flash(f"{form.username.data} has been added!")
        return redirect(url_for('dash'))
    return render_template('register.html', name = 'login', form=forms)

这是所需的模板信息:

<div class="form-group">
  {{form.sitechoices}}
</div>

我想从queryselectfield内的模型中检索站点名称,并能够使用该选定选项注册用户。

2 个答案:

答案 0 :(得分:2)

在queryselectfield中返回对象,因此您需要使用form.sitechoices.data.sitename来保存提交的表单

答案 1 :(得分:0)

我使用Flask,Blueprint,WTForms 3.0,SQLAlchemy,Bootstrap 4-以下语法对我有用...

FORMS.py

class IndicatorForm(FlaskForm):
    class Meta:
        csrf = False

    ind_id = IntegerField('indid', id='indid')
    topic = QuerySelectField('Topic',query_factory=lambda: Indicator.query.group_by("topic"), allow_blank=True, blank_text=u'Topic', get_pk=lambda a: a.id, get_label='topic')
    subtopic1 = QuerySelectField('SubTopic',query_factory=lambda: Indicator.query.group_by("subtopic1"), allow_blank=True, blank_text=u'SubTopic', get_pk=lambda a: a.id, get_label='subtopic1')

routes.py

@blueprint.route('/newind_edit', methods=['GET','POST'])
@login_required
def newind_edit():

    form = IndicatorForm(request.form) 

    if request.method == "POST" and form.validate():
        indid = request.form['ind_id']
        Indicator.query.filter_by(id=indid).update(dict(
            id=ind_id,
            topic = form.topic.name.topic,     # <== this is the selected value
            subtopic1 = form.subtopic1.name.subtopic1   #  <== add as many pull-downs as you like
            ))    
        db.session.commit()