A Very Simple Tornado WTForm Example using wtforms_tornado

Replacing a basic html form contained within a Tornado template with a WTForms form wasn’t as intuitive as I might have hoped (thus the name, WTF?). Nor was a template. I found an SO post which referenced the wtforms_tornado module, but use of the simple example posted on that page eludes me because there isn’t a front end web form included.

So for anyone else in the same position as I was – here’s a very simple of a Tornado app that simply displays a simple WTForms form (with some basic validation) and returns the request results to the browser screen, or returns a 404 with the validation error.

First insure that Tornado, WTForms and wtforms_tornado are installed, which can be seen by typing pip freeze into the console, which returns a list of all modules installed by pip. wtforms-tornado is installed with sudo pip install wtforms-tornado, likewise with WTForms (note case) and tornado.

We’ll need a directory for the form template itself to create a directory called templates and inside that directory make a files called simpleform.html containing the following code:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>

<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>A Simple Form</title>
<meta name=”description” content=”Submit Track to Infinite Glitch”>
</head>
<body>
<p><h1>Submit Info</h1></p>
<form enctype=”multipart/form-data” action=”/simple” method=”post”>
{{ form.name }}<br/>
{{ form.email }}<br/>
{{ form.message }}<br/>
<input type=”submit”/>
</form>
</body>
</html>

Then create the file to run the app (in the directory above templates). We’ll call is simpleform.py:


import wtforms
from wtforms_tornado import Form

class EasyForm(Form):
          name = wtforms.TextField('name', validators=[wtforms.validators.DataRequired()], default=u'test')
          email = wtforms.TextField('email', validators=[wtforms.validators.Email(), wtforms.validators.DataRequired()])
          message = wtforms.TextAreaField('message', validators=[wtforms.validators.DataRequired()])

class SimpleForm(tornado.web.RequestHandler):
    def get(self):
        form = EasyForm()
        self.write(templates.load("simpleform.html").generate(compiled=compiled, form=form))

    def post(self):
        form = EasyForm(self.request.arguments)
        details = '';
        if form.validate():
            for f in self.request.arguments:
                details += self.get_argument(f, default=None, strip=False)
            self.write(details)
        else:
            self.set_status(400)
            self.write(form.errors)
                
if __name__ == "__main__":
	
	application = tornado.web.Application(
		tornadio2.TornadioRouter(SocketConnection).apply_routes([
			(r"/simple", SimpleForm),
		]),
	)

    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

Then from the command line run python simpleform.py, open a browser and visit localhost:8888/simple and you should see our friendly, simple form.

Comments and input welcome.

3 responses to “A Very Simple Tornado WTForm Example using wtforms_tornado

  1. hi, i follow the steps but i get this error:
    File “simpleform.py”, line 9, in
    class SimpleForm(tornado.web.RequestHandler):
    NameError: name ‘tornado’ is not defined

      1. Hi. Did you install Tornado? `pip install tornado`. It also needs to be imported into your file: `import tornado.web`. Start with the Hello world example from the link above.

Comments are closed.