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(),
}
Your stack trace reads:
jinja2.exceptions.UndefinedError: 'login_user_form' is undefined
This error message is coming from Jinja, which is saying that login_user_form
is undefined.
To solve this, if this was your base.html
,
...
{% block content %}
<form action="" method="post" name="post">
{{form.hidden_tag()}}
...
you've to pass login_user_form
as a context variable to your render template. So, in your /login
route, you should return something like this:
return render_template("base.html",
title = 'Home',
form = login_user_form)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With