Skip to content

Instantly share code, notes, and snippets.

@tomekwojcik
Created May 3, 2011 09:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomekwojcik/953046 to your computer and use it in GitHub Desktop.
Save tomekwojcik/953046 to your computer and use it in GitHub Desktop.
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
Copy link

tkbrady 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
Copy link

AndreiD commented May 21, 2015

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

@senabhishek
Copy link

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

@albe-rosado
Copy link

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