如何在分配之前引用此变量?

时间:2017-11-10 03:45:49

标签: python flask

错误消息:UnboundLocalError:在赋值之前引用的局部变量'post_title'

我尝试在变量之前使用global,这导致语法错误。

相关代码:

class PostForm(Form):

    title = StringField('Title', [validators.Length(min=1, max=200)])

    body = TextAreaField('Body', [validators.Length(min=30)])

@is_logged_in
@app.route('/add_post', methods=['GET','POST'])
def add_post():
    form = PostForm(request.form)
    if request.method == 'POST' and form.validate():

        post_title = form.title.data
        body = form.body.data
        cur = mysql.connection.cursor()
        cur.execute('INSERT INTO posts(title, body, author) 
         VALUES(%s, %s, %s)',(post_title, body, session['username']))
        mysql.connection.commit()

        print(post_title)
        cur.close()
        flash('Post created', 'success')
        return redirect(url_for('dashboard'))
    return render_template('add_post.html', form=form)

Traceback

1 个答案:

答案 0 :(得分:-1)

我认为你错误地放置了验证检查。只有在通过POST请求提交表单时,表单才会显示值。试一试:

@is_logged_in
@app.route('/add_post', methods=['GET','POST'])
def add_post():
    form = PostForm()
    if request.method == "POST":
        if form.validate_on_submit():
            post_title = form.title.data
            body = form.body.data
            cur = mysql.connection.cursor()
            cur.execute('INSERT INTO posts(title, body, author) VALUES(%s, %s, %s)',\
                        (post_title, body, session['username']))
            mysql.connection.commit()
            cur.close()
            flash('Post created', 'success')
            return redirect(url_for('dashboard'))
        else:
            flash("Form validation failed")
    return render_template('add_post.html', form=form)

N.B。:Difference between form.validate_on_submit() and form.validate()

的答案很好