Showing error messages helps users understand what went wrong. It guides them to fix mistakes easily.
0
0
Error message display in templates in Flask
Introduction
When a user submits a form with missing or wrong information.
When login fails due to incorrect username or password.
When a required field is left empty in a web form.
When server-side validation finds invalid data.
When you want to give feedback after user actions.
Syntax
Flask
{% if error_message %}
<div class="error">{{ error_message }}</div>
{% endif %}Use Jinja2 template syntax to check if an error message exists.
Place the error message inside a visible HTML element for styling.
Examples
Show a paragraph with the error text if the variable
error is set.Flask
{% if error %}
<p class="error">{{ error }}</p>
{% endif %}Display a list of all form field errors when using Flask-WTF forms.
Flask
{% if form.errors %}
<ul class="error-list">
{% for field, errors in form.errors.items() %}
{% for error in errors %}
<li>{{ field }}: {{ error }}</li>
{% endfor %}
{% endfor %}
</ul>
{% endif %}Sample Program
This Flask app shows a simple form asking for a name. If the user submits without typing a name, it shows an error message in red above the form. If a name is entered, it greets the user.
The error message uses ARIA roles for accessibility and appears only when needed.
Flask
from flask import Flask, render_template_string, request app = Flask(__name__) html_template = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Form</title> <style> .error { color: red; font-weight: bold; } </style> </head> <body> <h1>Enter your name</h1> {% if error_message %} <div class="error" role="alert" aria-live="assertive">{{ error_message }}</div> {% endif %} <form method="POST"> <label for="name">Name:</label> <input type="text" id="name" name="name" aria-describedby="error-msg"> <button type="submit">Submit</button> </form> </body> </html> ''' @app.route('/', methods=['GET', 'POST']) def index(): error_message = None if request.method == 'POST': name = request.form.get('name', '').strip() if not name: error_message = 'Please enter your name.' else: return f'Hello, {name}!' return render_template_string(html_template, error_message=error_message) if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Always escape error messages to avoid security issues.
Use ARIA roles like role="alert" and aria-live="assertive" to help screen readers announce errors immediately.
Style error messages clearly with colors and spacing to catch user attention.
Summary
Error messages help users fix problems quickly.
Use Jinja2 conditions to show errors only when they exist.
Make error messages accessible and visually clear.