使用Flask-Security提供的示例代码,我可以正常访问login_user.html
路径中的/login
表单,并且运行正常。但是,我想在左上角的所有网站页面上嵌入登录表单。我以为我可以使用Jinja {% include "security/login_user.html" %}
语句将表单放在base.html
中,但这似乎不起作用。我收到以下错误:
jinja2.exceptions.UndefinedError: 'login_user_form' is undefined
有没有办法在另一个模板中包含或嵌入登录表单,仍然可以访问相应的表单对象?
答案 0 :(得分:11)
security/login_user.html
是登录表单的完整页面模板。这不是你想要嵌入每个页面的东西,因为它处理其他东西,比如闪烁的消息,错误和布局。
编写您自己的模板以仅呈现表单并包含 ,或将其添加到您的基本模板。
<form action="{{ url_for_security('login') }}" method="POST">
{{ login_user_form.hidden_tag() }}
{{ login_user_form.email(placeholder='Email') }}
{{ login_user_form.password(placeholder='Password') }}
{{ login_user_form.remember.label }} {{ login_user_form.remember }}
{{ login_user_form.submit }}
</form>
(这只是一个例子,你需要设置它以适合你的页面。)
您的所有观点都不会直接处理登录表单,因此在呈现大多数模板时login_form
和url_for_security
不可用(这导致您观察到的原始问题)。使用app.context_processor
为每个请求注入它们。
from flask_security import LoginForm, url_for_security
@app.context_processor
def login_context():
return {
'url_for_security': url_for_security,
'login_user_form': LoginForm(),
}
答案 1 :(得分:1)
您的堆栈跟踪内容如下:
jinja2.exceptions.UndefinedError: 'login_user_form' is undefined
此错误消息来自Jinja,它说login_user_form
未定义。
要解决此问题,如果这是您的base.html
,
...
{% block content %}
<form action="" method="post" name="post">
{{form.hidden_tag()}}
...
您已将login_user_form
作为上下文变量传递到渲染模板。因此,在/login
路线中,您应该返回以下内容:
return render_template("base.html",
title = 'Home',
form = login_user_form)