【发布时间】: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块内?