如何通过WTForm编辑类实例

时间:2014-10-15 18:52:33

标签: python flask-sqlalchemy flask-wtforms

我正在尝试设置一个设置页面,其中当前登录的用户可以调整用户类的一些(当前是两个)属性。我正在使用SQLAlchemy来处理我的数据库查询。设置页面和表单在我尝试绑定用户类之前显示和工作,因此我认为这是我的Flask代码的问题。我试图遵循WTForms crash course documentation中的示例代码,但仍然导致错误。任何帮助或指导将不胜感激。

烧瓶代码:

class SettingsForm(Form):
    topics = TextField('Topics')
    emailFrequency= RadioField('Email Frequency', choices = [('Daily', u'Daily'), ('Weekly', u'Weekly'), ('Monthly', u'Monthly'), ('Never', u'Never')], default='Weekly')
    submit = SubmitField("Save Changes")

@application.route('/settings', methods = ['GET', 'POST'])
@login_required
def settings(request):
    user = current_user
    form = SettingsForm(request.form)
    if request.method == 'POST' and form.validate():
        user.emailFrequency = form.emailFrequency.data 
        user.topics = form.topics.data
        db.session.commit()
        return render_template('settings.html', page_title = "Success", form=form, success=True)
    elif request.method == 'GET':
        return render_template('settings.html', page_title = 'Customize your settings using the form below', form = form)

HTML

{% extends "base-layout.html" %}

{% block content %}
    {% if success %}
        <h2> Settings updated! </h2>
    {% else %}
        <h2> Customize your settings</h2>
         <form class="form" action="{{url_for('settings')}}" method="POST" role="form">
            {{form.hidden_tag()}}
            <div> {{form.topics.label}} </div>
            <div> {{form.topics(placeholder="E.g. Gas, Oil, Renewables", class="form-control")}} </div>
            <div> {{form.emailFrequency.label}} </div>
            <div> {{form.emailFrequency}} </div>
            <div> {{form.submit}} </div>
        </form>
    {% endif %}
{% endblock %}

1 个答案:

答案 0 :(得分:0)

希望如果其他人有同样的问题,这会有所帮助,当我将请求输入删除到设置功能时,表单有效:

@application.route('/settings', methods = ['GET', 'POST'])
@login_required
def settings():
    user = current_user
    form = SettingsForm(request.form)
    if request.method == 'POST' and form.validate():
        user.emailFrequency = form.emailFrequency.data 
        user.topics = form.topics.data
        db.session.commit()
        return render_template('settings.html', page_title = "Success", form=form, success=True)
    elif request.method == 'GET':
        return render_template('settings.html', page_title = 'Customize your settings using the form below', form = form)

如果有人想解释为什么会有效,那将来会有所帮助。