pallets-eco/flask-wtf

clarification in docs of validate_on_sumbit() and csrf_token

Opened this issue · 0 comments

Hi All,

Being new to flask-wtf, I've some question/suggestion regarding the docs.

I wanted to implement a form with a submit button. After pressing the button some function needs to be executed. This was already a challenge to me. Searching StackOverflow the validate_on_submit was frequently mentioned as a method to put in my view function.

After some tweaking I have found out that putting {{ form.csrf_token }} is required in order to work with validate_on_submit. However this was not something clear from the documentation for me.

Suggestion

Perhaps in the validate_on_submit docs add the following

In order to validate on submit, you need to provide the csrf_token within template containing the form.

Like to recieve your feedback and thoughts.

Example app

# app.py
from flask import Flask, render_template, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import SubmitField

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

class MyForm(FlaskForm):
    submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = MyForm()

    if form.validate_on_submit():
        # Perform some action upon form submission
        return redirect(url_for('success'))

    return render_template('index.html.jinja', form=form)

@app.route('/success')
def success():
    return 'Form submitted successfully!'
{# index.html.jinja #}
<!DOCTYPE html>
<html>
<head>
    <title>Submit Field Example</title>
</head>
<body>
    <h1>Submit Field Example</h1>
    <form method="POST" action="/">
        {{ form.csrf_token }}
        {{ form.submit() }}
    </form>
</body>
</html>