0Pricing
Flask Academy · Lezione

validate_on_submit e token CSRF

Elabori i POST validi e blocchi le falsificazioni.

validate_on_submit e token CSRF è una lezione Flask Academy gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flask Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flask Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

The Golden Method

Flask-WTF gives you one method that checks everything at once. validate_on_submit is the heart of safely processing any form. 🔑

What It Actually Checks

validate_on_submit returns True only when the request is a POST and every validator passes. One call covers both conditions.

if form.validate_on_submit():
    pass  # safe to use the data

The Standard View Pattern

This shape repeats in every Flask app: build the form, branch on validate_on_submit, then fall through to render the page.

form = LoginForm()
if form.validate_on_submit():
    return redirect('/home')
return render_template('login.html', form=form)

Submitted vs Valid

Do not confuse the two. is_submitted only checks the method, while validate_on_submit also confirms the data passed every rule.

form.is_submitted()        # POST? 
form.validate_on_submit()  # POST and valid?

Why CSRF Matters

A CSRF attack tricks a logged-in user into submitting a form they never meant to. Tokens prove the request came from your own page.

SECRET_KEY Is Required

CSRF tokens are signed, so Flask needs a SECRET_KEY. Without it, validation fails and Flask-WTF refuses to protect the form.

app.config['SECRET_KEY'] = 'change-me-in-production'

The Token in the Page

That call to hidden_tag embeds the signed token as a hidden input. The browser sends it back with every submission.

{{ form.hidden_tag() }}

Validation Compares Tokens

On submit, Flask-WTF compares the posted token against the session. A missing or stale token makes validate_on_submit return False.

if not form.validate_on_submit():
    pass  # bad token or failed rule

Inspect Why It Failed

When validation fails, look at form.errors. It maps each field name to the list of messages explaining the problem.

if not form.validate_on_submit():
    print(form.errors)

Process Then Redirect

After a successful submit, finish with a redirect. That follows the PRG pattern and stops a refresh from posting twice.

if form.validate_on_submit():
    save(form.data)
    return redirect('/done')

Never Disable CSRF Blindly

You can turn off CSRF for APIs, but never for browser forms. Keeping protection on is what makes Flask-WTF worth using.

Quick Check

When does form.validate_on_submit() return True?

Recap

You leaned on validate_on_submit for the method-plus-rules check, set a SECRET_KEY for signed CSRF tokens, and redirected after success. 🛡️

Domande Frequenti

La lezione «validate_on_submit e token CSRF» è gratuita?

Sì — il testo completo di «validate_on_submit e token CSRF» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flask Academy, passa a CoddyKit PRO. Il corso Flask Academy include 4 lezioni in totale.

Cosa imparerò in «validate_on_submit e token CSRF»?

Elabori i POST validi e blocchi le falsificazioni. Eserciti Flask Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Flask Academy?

Non è richiesta alcuna esperienza precedente. Flask Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «validate_on_submit e token CSRF»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Flask Academy?

Sì. Ogni lezione Flask Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Definire una classe FlaskForm
  2. Renderizzare e inviare un form
  3. validate_on_submit e token CSRF
  4. Validator personalizzati ed errori dei campi
← Torna a Flask Academy