Showing error messages helps users understand what went wrong. It guides them to fix mistakes easily.
Error message display in templates in Flask
{% if error_message %}
<div class="error">{{ error_message }}</div>
{% endif %}error is set.{% if error %}
<p class="error">{{ error }}</p>
{% endif %}{% 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 %}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.
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)
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.
Error messages help users fix problems quickly.
Use Jinja2 conditions to show errors only when they exist.
Make error messages accessible and visually clear.
Practice
Solution
Step 1: Understand template logic in Flask
Flask uses Jinja2 templating, which supports{% if %}statements to conditionally render content.Step 2: Use Jinja2 syntax to check error existence
Inside the template, you write{% if error %}to check if the error variable has a value before showing it.Final Answer:
Use a Jinja2 {% if error %} condition to check if the error variable is set. -> Option DQuick Check:
Jinja2 if condition = B [OK]
- Trying to use Python if statements directly in templates
- Displaying errors without checking if they exist
- Using JavaScript inside templates for error display
error inside a Flask template?Solution
Step 1: Recall Jinja2 variable display syntax
In Flask templates, variables are shown using double curly braces like{{ variable }}.Step 2: Apply to the error variable
To display the error message stored inerror, use{{ error }}.Final Answer:
{{ error }} -> Option AQuick Check:
Variable display uses {{ }} = A [OK]
- Using {% %} which is for logic, not display
- Using incorrect brackets like [[ ]]
- Trying to use custom tags like {% display %}
{% if errors %}
{{ errors[0] }}
{% endif %}And the variable
errors is a list: ["Invalid email"], what will be rendered?Solution
Step 1: Check the condition {% if errors %}
The listerrorscontains one item, so it is truthy and the block runs.Step 2: Render the first error message
The template outputs{{ errors[0] }}which is "Invalid email" inside a div with class "error".Final Answer:
<div class="error">Invalid email</div> -> Option CQuick Check:
Truthy list shows first error = C [OK]
- Thinking lists can't be checked in if conditions
- Expecting literal text 'errors[0]' instead of value
- Assuming syntax error due to list indexing
{% if error %}
{{ error }}
{% endif %}But no error message shows even when you pass
error='Invalid input' from Flask. What is the likely problem?Solution
Step 1: Check variable names consistency
If the Flask code passeserrorbut the template uses a different variable name or none, the condition fails.Step 2: Confirm template uses the exact variable name
The template must use the same variable nameerrorto display the message correctly.Final Answer:
Variable name mismatch causes no display. -> Option BQuick Check:
Variable name mismatch = D [OK]
- Assuming error is an object needing .message
- Thinking {% if %} syntax is wrong
- Believing Flask templates can't show errors
errors with accessible markup?Solution
Step 1: Check for errors existence before display
Using{% if errors %}ensures the list is not empty before rendering.Step 2: Loop through errors with
Each error is shown in a list item inside a{% for %}and use accessible markup<ul>witharia-live="polite"for screen readers.Final Answer:
{% if errors %} with {% for %} loop in accessible <ul aria-live="polite"> -> Option AQuick Check:
Check if errors + loop + aria-live = A [OK]
- Not checking if errors exist before looping
- Displaying the whole list as a string
- Missing accessibility attributes for screen readers
Ready to prove it?
Pass the test and this pattern moves unknown
