简体   繁体   English

如何修复“UnboundLocalError:赋值前引用的局部变量‘books’”?

[英]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.

相关问题 如何修复 UnboundLocalError:在 Python 中分配之前引用的局部变量“df” - How to fix UnboundLocalError: local variable 'df' referenced before assignment in Python 如何修复 UnboundLocalError:赋值前引用的局部变量“o1” - How to fix UnboundLocalError: local variable 'o1' referenced before assignment 如何解决Python错误:“ UnboundLocalError:分配前已引用本地变量'id1'” - How to fix Python error : “UnboundLocalError: local variable 'id1' referenced before assignment” 您如何解决:“UnboundLocalError:分配前引用的局部变量‘事件’”在 pygame 中? - How do you fix: "UnboundLocalError: local variable 'events' referenced before assignment" in pygame? 我该如何解决:UnboundLocalError:分配前引用的局部变量“生成” - how can i fix: UnboundLocalError: local variable 'generate' referenced before assignment 如何修复“UnboundLocalError:分配前引用的局部变量'user_score'”? - How can I fix "UnboundLocalError: local variable 'user_score' referenced before assignment"? 如何修复写入文件中的“UnboundLocalError:赋值前引用的局部变量‘open’”? - How to fix "UnboundLocalError: local variable 'open' referenced before assignment" in write file? 如何解决:“ UnboundLocalError:分配前已引用局部变量'all_sprites'” - How to fix: “UnboundLocalError: local variable 'all_sprites' referenced before assignment” 如何修复我的代码中的“UnboundLocalError:分配前引用的局部变量“dc”? - How do I fix 'UnboundLocalError: local variable 'dc' referenced before assignment' in my code? 如何解决此错误“UnboundLocalError:分配前引用的局部变量'a'” - How can I fix this error “UnboundLocalError: local variable 'a' referenced before assignment”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM