如何在我的页面上嵌入Flask-Security登录表单? [英] How do I embed a Flask-Security login form on my page?
问题描述
使用Flask-Security提供的示例代码,我可以从 / login
访问 login_user.html
>正常路线,工作得很好。不过,我想将登录表单嵌入到我左侧所有网站的页面中。我想我可以使用Jinja {%includesecurity / login_user.html%}
语句将表单放置在 base.html
,但似乎没有工作。我得到以下错误:
pre $ jinja2.exceptions.UndefinedError:'login_user_form'是未定义的
$ c $有没有一种方法来包含或嵌入到另一个模板的登录表单,仍然可以访问各自的表单对象?
编写自己的模板来呈现表单并将 包含进来,或者将其添加到您的基本模板中。 < 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
$ b @ app.context_processor
def login_context():
return {
'url_for_security':url_for_security,$ b $'login_user_form':LoginForm ),
}
Using the example code provided by Flask-Security, I can access the login_user.html
form from the /login
route normally and that works just fine. However, I would like to embed the login form on all my site's pages in the upper left. I thought I could use a Jinja {% include "security/login_user.html" %}
statement to place the form in base.html
, but that doesn't seem to work. I get the following error:
jinja2.exceptions.UndefinedError: 'login_user_form' is undefined
Is there a way to include or embed the login form inside another template and still get access to the respective form object?
security/login_user.html
is the full page template for the login form. It's not what you would want to embed on each page because it deals with other things like flashed messages, errors, and layout.
Write your own template to render just the form and include that, or add it to your base template.
<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>
(This is just an example, you'll want to style it to fit your page.)
None of your views will deal with the login form directly, so login_form
and url_for_security
aren't available while rendering most templates (this was causing the original issue you observed). Inject them for each request using 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(),
}
这篇关于如何在我的页面上嵌入Flask-Security登录表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!