How do I embed a Flask-Security login form on my page? How do I embed a Flask-Security login form on my page? flask flask

How do I embed a Flask-Security login form on my page?


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_processordef 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)