← Back to Python

All Topics

Advertisement

Learn/Python/Web Development

Flask Templates and Forms

Topic: Flask

Advertisement

Introduction

Render HTML templates and handle form data in Flask applications.

Templates

from flask import render_template

@app.route("/")
def index():
    return render_template("index.html", title="Home")

# In template (index.html)
# {{ title }}
# {% for item in items %}
#   <li>{{ item }}</li>
# {% endfor %}

Jinja2 Template Engine

<!-- Variables -->
{{ name }}
{{ user.age }}

<!-- Conditionals -->
{% if user.logged_in %}
  Welcome, {{ user.name }}!
{% else %}
  Please log in.
{% endif %}

<!-- Filters -->
{{ name|upper }}
{{ date|datetime }}

Form Handling

from flask import request, redirect, url_for

@app.route("/submit", methods=["GET", "POST"])
def submit():
    if request.method == "POST":
        name = request.form["name"]
        email = request.form["email"]
        return redirect(url_for("success"))
    return render_template("form.html")

Practice Problems

  1. Create template inheritance
  2. Handle form submission
  3. Use Jinja2 filters
  4. Display flash messages
  5. Implement CSRF protection

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →