【问题标题】:How is this variable referenced before it is assigned?这个变量在赋值之前是如何引用的?
【发布时间】:2017-11-10 15:03:53
【问题描述】:

错误消息: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)

【问题讨论】:

  • 看起来缩进很乱,你应该重新格式化代码。
  • 你的缩进很奇怪。 猜测if request.method == 'POST' and form.validate(): 必须是 True,然后 post_title 当前存在。如果if 检查不正确,您永远不会定义post_title,但同样,您需要修复缩进以确保这一点。
  • 我的错。代码中不是这样的。编辑不好。
  • 如果您推荐 cur.execute 行并只执行 print(post_title) 会发生什么?
  • cur.execute(...) 在您的实际代码中肯定缩进到 if 块内?

标签: python flask


【解决方案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)

注意:Difference between form.validate_on_submit() and form.validate() 上的一个很好的答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2015-04-22
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多