[英]How to fix "UnboundLocalError: local variable 'books' referenced before assignment"?
I'm new to python and currently trying to display data from my database to my homepage but I am getting the above named error.我是 python 的新手,目前正在尝试将数据从我的数据库显示到我的主页,但我收到了上面命名的错误。
I'm running Python 3.7.我正在运行 Python 3.7。 I've tried setting 'books' as a global variable but I end up with a different Name error [Name "books" not defined].
我尝试将“books”设置为全局变量,但最终得到了不同的 Name 错误 [Name "books" not defined]。
@app.route("/", methods=["GET", "POST"])
def home():
if request.form:
book = Book(title=request.form.get("title"))
db.session.add(book)
db.session.commit()
books = Book.query.all()
return render_template("home.html", books=books)
I expect when a user loads the home page, all books currently in the database are displayed in a form but instead I get the above error(s).我希望当用户加载主页时,当前数据库中的所有书籍都显示在表单中,但我收到了上述错误。
Change your code to this将您的代码更改为此
@app.route("/", methods=["GET", "POST"])
def home():
books = {}
if request.form:
book = Book(title=request.form.get("title"))
db.session.add(book)
db.session.commit()
books = Book.query.all()
return render_template("home.html", books=books)
And let me know what happens让我知道会发生什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.