Rendering Flask-WTF forms in templates
Explore how to render Flask-WTF forms in templates by passing form objects from views to Jinja templates. Understand how to include form fields and labels using Jinja syntax, and implement CSRF protection with Flask-WTF's csrf_token. This lesson helps you modify views and templates to render working login forms securely using the Flask framework.
To render the form, we first need to return it from a view to the template.
Modify login view in app.py
Now let’s modify the application module to use the forms.
Import LoginForm
Let’s first import the LoginForm from the forms module forms.py.
from forms import LoginForm
Create an object of LoginForm in the login view
We will then create an object of this form inside the login route.
@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
Return the form to the template
This form will be passed to the render_template function as a named argument.
return render_template("login.html", form = form)