Forms in Templates
Forms are how you collect data from users. In Flask templates, you create standard HTML forms, but use Jinja2's url_for() function to set the form's action attribute. This keeps your URLs flexible and clean.
Here's a simple login form in a template:
<form method="POST" action="{{ url_for('login') }}">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
When the form is submitted, the data goes to the route defined in url_for('login'). In that route, you access the data using request.form:
from flask import Flask, render_template, request, redirect, url_for
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# Process login...
return redirect(url_for('welcome'))
return render_template('login.html')
You can pre-fill form values by setting the value attribute with Jinja2. This is useful when editing existing data:
<input type="text" name="username" value="{{ user.username }}">
For displaying submitted data back to the user (like after an error), you can use the same request.form:
<input type="text" name="username" value="{{ request.form.username }}">
Error messages are important for good user experience. You can display them conditionally:
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
{% if error %}
<p class="error">{{ error }}</p>
{% endif %}
</div>
For file uploads, add the enctype attribute to your form tag. This tells the browser to send the file data properly:
<form method="POST" action="{{ url_for('upload') }}" enctype="multipart/form-data">
<input type="file" name="document">
<button type="submit">Upload</button>
</form>
Without that enctype attribute, your file uploads won't work. Always include it when your form has file inputs.
Try it Yourself ->