Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flask mini-app demoing WTForms reuse
from flask import Flask, render_template, flash, request
from werkzeug.datastructures import MultiDict
from flaskext.wtf import Form, TextField, TextAreaField, validators
# App config.
DEBUG = True
SECRET_KEY = '87469976308fd14a2d0148247d441f2756b6176a'
app = Flask(__name__)
app.config.from_object(__name__)
class ReusableForm(Form):
name = TextField('Name:', validators=[validators.required()])
email = TextField('E-mail:', validators=[validators.required(), validators.email()])
comment = TextAreaField('Comment:', validators=[validators.required()])
def reset(self):
blankData = MultiDict([ ('csrf', self.reset_csrf() ) ])
self.process(blankData)
@app.route("/", methods=['GET', 'POST'])
def hello():
form = ReusableForm()
if request.method == 'POST':
if form.validate():
# Save the comment here.
flash('Comment saved.')
form.reset()
else:
flash('All the form fields are required.')
return render_template('hello.html', form=form)
if __name__ == "__main__":
app.run()
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Reusable Form Demo</title>
</head>
<body>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message[1] }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form action="" method="post">
{{ form.csrf }}
<div class="input text">
{{ form.name.label }} {{ form.name }}
</div>
<div class="input text">
{{ form.email.label }} {{ form.email }}
</div>
<div class="input textarea">
{{ form.comment.label }} {{ form.comment }}
</div>
<div class="input submit">
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
@tkbrady

This comment has been minimized.

Copy link

commented Oct 6, 2014

I can't seem to find documentation on the reset_csrf() function. Do you know if this solution works with the current version of flask?

@AndreiD

This comment has been minimized.

Copy link

commented May 21, 2015

AtributeError: 'MyForm' object has no attribute 'reset_csrf'

@senabhishek

This comment has been minimized.

Copy link

commented Jan 13, 2016

I am getting the same error - blankData = MultiDict([ ('csrf', self.reset_csrf() ) ])
AttributeError: 'xxx' object has no attribute 'reset_csrf'

@albe-rosado

This comment has been minimized.

Copy link

commented Nov 12, 2016

def reset(self): blankData = MultiDict([ ('csrf', self.generate_csrf_token() ) ]) self.process(blankData)
just replace "reset_csrf()" with "generate_csrf_token()" ....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.