2012-05-13T06:26:42Z

The Flask Mega-Tutorial, Part III: Web Forms

(Great news! There is a new version of this tutorial!)

This is the third article in the series in which I document my experience writing web applications in Python using the Flask microframework.

The goal of the tutorial series is to develop a decently featured microblogging application that demonstrating total lack of originality I have decided to call microblog.

NOTE: This article was revised in September 2014 to be in sync with current versions of Python and Flask.

Here is an index of all the articles in the series that have been published to date:

Recap

In the previous chapter of the series we defined a simple template for the home page and used fake objects as placeholders for things we don't have yet, like users or blog posts.

In this article we are going to fill one of those many holes we still have in our app, we will be looking at how to work with web forms.

Web forms are one of the most basic building blocks in any web application. We will be using forms to allow users to write blog posts, and also for logging in to the application.

To follow this chapter along you need to have the microblog app as we left it at the end of the previous chapter. Please make sure the app is installed and running.

Configuration

To handle our web forms we are going to use the Flask-WTF extension, which in turn wraps the WTForms project in a way that integrates nicely with Flask apps.

Many Flask extensions require some amount of configuration, so we are going to setup a configuration file inside our root microblog folder so that it is easily accessible if it needs to be edited. Here is what we will start with (file config.py):

WTF_CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'

Pretty simple, it's just two settings that our Flask-WTF extension needs. The WTF_CSRF_ENABLED setting activates the cross-site request forgery prevention (note that this setting is enabled by default in current versions of Flask-WTF). In most cases you want to have this option enabled as it makes your app more secure.

The SECRET_KEY setting is only needed when CSRF is enabled, and is used to create a cryptographic token that is used to validate a form. When you write your own apps make sure to set the secret key to something that is difficult to guess.

Now that we have our config file we need to tell Flask to read it and use it. We can do this right after the Flask app object is created, as follows (file app/__init__.py):

from flask import Flask

app = Flask(__name__)
app.config.from_object('config')

from app import views

The user login form

Web forms are represented in Flask-WTF as classes, subclassed from base class Form. A form subclass simply defines the fields of the form as class variables.

Now we will create a login form that users will use to identify with the system. The login mechanism that we will support in our app is not the standard username/password type, we will have our users login using their OpenID. OpenIDs have the benefit that the authentication is done by the provider of the OpenID, so we don't have to validate passwords, which makes our site more secure to our users.

The OpenID login only requires one string, the so called OpenID. We will also throw a 'remember me' checkbox in the form, so that users can choose to have a cookie installed in their browsers that remembers their login when they come back.

Let's write our first form (file app/forms.py):

from flask_wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired

class LoginForm(Form):
    openid = StringField('openid', validators=[DataRequired()])
    remember_me = BooleanField('remember_me', default=False)

I believe the class is pretty much self-explanatory. We imported the Form class, and the two form field classes that we need, StringField and BooleanField.

The DataRequired import is a validator, a function that can be attached to a field to perform validation on the data submitted by the user. The DataRequired validator simply checks that the field is not submitted empty. There are many more validators included with Flask-WTF, we will use some more in the future.

Form templates

We will also need a template that contains the HTML that produces the form. The good news is that the LoginForm class that we just created knows how to render form fields as HTML, so we just need to concentrate on the layout. Here is our login template (file app/templates/login.html):

<!-- extend from base layout -->
{% extends "base.html" %}

{% block content %}
  <h1>Sign In</h1>
  <form action="" method="post" name="login">
      {{ form.hidden_tag() }}
      <p>
          Please enter your OpenID:<br>
          {{ form.openid(size=80) }}<br>
      </p>
      <p>{{ form.remember_me }} Remember Me</p>
      <p><input type="submit" value="Sign In"></p>
  </form>
{% endblock %}

Note that in this template we are reusing the base.html template through the extends template inheritance statement. We will actually do this with all our templates, to ensure a consistent layout across all pages.

There are a few interesting differences between a regular HTML form and our template. This template expects a form object instantiated from the form class we just defined stored in a template argument named form. We will take care of sending this template argument to the template next, when we write the view function that renders this template.

The form.hidden_tag() template argument will get replaced with a hidden field that implements the CSRF prevention that we enabled in the configuration. This field needs to be in all your forms if you have CSRF enabled. The good news is that Flask-WTF handles it for us, we just need to make sure it is included in the form.

The actual fields of our form are rendered by the field objects, we just need to refer to a {{form.field_name}} template argument in the place where each field should be inserted. Some fields can take arguments. In our case, we are asking the text field to generate our openid field with a width of 80 characters.

Since we have not defined the submit button in the form class we have to define it as a regular field. The submit field does not carry any data so it doesn't need to be defined in the form class.

Form views

The final step before we can see our form is to code a view function that renders the template.

This is actually quite simple since we just need to pass a form object to the template. Here is our new view function (file app/views.py):

from flask import render_template, flash, redirect
from app import app
from .forms import LoginForm

# index view function suppressed for brevity

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    return render_template('login.html', 
                           title='Sign In',
                           form=form)

So basically, we have imported our LoginForm class, instantiated an object from it, and sent it down to the template. This is all that is required to get form fields rendered.

Let's ignore for now the flash and redirect imports. We'll use them a bit later.

The only other thing that is new here is the methods argument in the route decorator. This tells Flask that this view function accepts GET and POST requests. Without this the view will only accept GET requests. We will want to receive the POST requests, these are the ones that will bring in the form data entered by the user.

At this point you can try the app and see the form in your web browser. After you start the application you will want to open http://localhost:5000/login in your web browser, as this is the route we have associated with the login view function.

We have not coded the part that accepts data yet, so pressing the submit button will not have any effect at this time.

Receiving form data

Another area where Flask-WTF makes our job really easy is in the handling of the submitted form data. Here is an updated version of our login view function that validates and stores the form data (file app/views.py):

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash('Login requested for OpenID="%s", remember_me=%s' %
              (form.openid.data, str(form.remember_me.data)))
        return redirect('/index')
    return render_template('login.html', 
                           title='Sign In',
                           form=form)

The validate_on_submit method does all the form processing work. If you call it when the form is being presented to the user (i.e. before the user got a chance to enter data on it) then it will return False, so in that case you know that you have to render the template.

When validate_on_submit is called as part of a form submission request, it will gather all the data, run all the validators attached to fields, and if everything is all right it will return True, indicating that the data is valid and can be processed. This is your indication that this data is safe to incorporate into the application.

If at least one field fails validation then the function will return False and that will cause the form to be rendered back to the user, and this will give the user a chance to correct any mistakes. We will see later how to show an error message when validation fails.

When validate_on_submit returns True our login view function calls two new functions, imported from Flask. The flash function is a quick way to show a message on the next page presented to the user. In this case we will use it for debugging, since we don't have all the infrastructure necessary to log in users yet, we will instead just display a message that shows the submitted data. The flash function is also extremely useful on production servers to provide feedback to the user regarding an action.

The flashed messages will not appear automatically in our page, our templates need to display the messages in a way that works for the site layout. We will add these messages to the base template, so that all our templates inherit this functionality. This is the updated base template (file app/templates/base.html):

<html>
  <head>
    {% if title %}
    <title>{{ title }} - microblog</title>
    {% else %}
    <title>microblog</title>
    {% endif %}
  </head>
  <body>
    <div>Microblog: <a href="/index">Home</a></div>
    <hr>
    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul>
        {% for message in messages %}
            <li>{{ message }} </li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}
    {% block content %}{% endblock %}
  </body>
</html>

The technique to display the flashed message is hopefully self-explanatory. One interesting property of flash messages is that once they are requested through the get_flashed_messages function they are removed from the message list, so these messages appear in the first page requested by the user after the flash function is called, and then they disappear.

The other new function we used in our login view is redirect. This function tells the client web browser to navigate to a different page instead of the one requested. In our view function we use it to redirect to the index page we developed in previous chapters. Note that flashed messages will display even if a view function ends in a redirect.

This is a great time to start the app and test how the form works. Make sure you try submitting the form with the openid field empty, to see how the DataRequired validator halts the submission process.

Improving field validation

With the app in its current state, forms that are submitted with invalid data will not be accepted. Instead, the form will be presented back to the user to correct. This is exactly what we want.

What we are missing is an indication to the user of what is wrong with the form. Luckily, Flask-WTF also makes this an easy task.

When a field fails validation Flask-WTF adds a descriptive error message to the form object. These messages are available to the template, so we just need to add a bit of logic that renders them.

Here is our login template with field validation messages (file app/templates/login.html):

<!-- extend base layout -->
{% extends "base.html" %}

{% block content %}
  <h1>Sign In</h1>
  <form action="" method="post" name="login">
      {{ form.hidden_tag() }}
      <p>
          Please enter your OpenID:<br>
          {{ form.openid(size=80) }}<br>
          {% for error in form.openid.errors %}
            <span style="color: red;">[{{ error }}]</span>
          {% endfor %}<br>
      </p>
      <p>{{ form.remember_me }} Remember Me</p>
      <p><input type="submit" value="Sign In"></p>
  </form>
{% endblock %}

The only change we've made is to add a for loop that renders any messages added by the validators below the openid field. As a general rule, any fields that have validators attached will have errors added under form.field_name.errors. In our case we use form.openid.errors. We display these messages in a red style to call the user's attention.

Dealing with OpenIDs

In practice, we will find that a lot of people don't even know that they already have a few OpenIDs. It isn't that well known that a number of major service providers on the Internet support OpenID authentication for their members. For example, if you have an account with Google, you have an OpenID with them. Likewise with Yahoo, AOL, Flickr and many other providers. (Update: Google is shutting down their OpenID service on April 15 2015).

To make it easier for users to login to our site with one of these commonly available OpenIDs, we will add links to a short list of them, so that the user does not have to type the OpenID by hand.

We will start by defining the list of OpenID providers that we want to present. We can do this in our config file (file config.py):

WTF_CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'

OPENID_PROVIDERS = [
    {'name': 'Google', 'url': 'https://www.google.com/accounts/o8/id'},
    {'name': 'Yahoo', 'url': 'https://me.yahoo.com'},
    {'name': 'AOL', 'url': 'http://openid.aol.com/<username>'},
    {'name': 'Flickr', 'url': 'http://www.flickr.com/<username>'},
    {'name': 'MyOpenID', 'url': 'https://www.myopenid.com'}]

Now let's see how we use this array in our login view function:

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash('Login requested for OpenID="%s", remember_me=%s' %
              (form.openid.data, str(form.remember_me.data)))
        return redirect('/index')
    return render_template('login.html', 
                           title='Sign In',
                           form=form,
                           providers=app.config['OPENID_PROVIDERS'])

Here we grab the configuration by looking it up in app.config with its key. The array is then added to the render_template call as a template argument.

As I'm sure you guessed, we have one more step to be done with this. We now need to specify how we would like to render these provider links in our login template (file app/templates/login.html):

<!-- extend base layout -->
{% extends "base.html" %}

{% block content %}
<script type="text/javascript">
function set_openid(openid, pr)
{
    u = openid.search('<username>')
    if (u != -1) {
        // openid requires username
        user = prompt('Enter your ' + pr + ' username:')
        openid = openid.substr(0, u) + user
    }
    form = document.forms['login'];
    form.elements['openid'].value = openid
}
</script>
<h1>Sign In</h1>
<form action="" method="post" name="login">
    {{ form.hidden_tag() }}
    <p>
        Please enter your OpenID, or select one of the providers below:<br>
        {{ form.openid(size=80) }}
        {% for error in form.openid.errors %}
          <span style="color: red;">[{{error}}]</span>
        {% endfor %}<br>
        |{% for pr in providers %}
          <a href="javascript:set_openid('{{ pr.url }}', '{{ pr.name }}');">{{ pr.name }}</a> |
        {% endfor %}
    </p>
    <p>{{ form.remember_me }} Remember Me</p>
    <p><input type="submit" value="Sign In"></p>
</form>
{% endblock %}

The template got somewhat long with this change. Some OpenIDs include the user's username, so for those we have to have a bit of javascript magic that prompts the user for the username and then composes the OpenID with it. When the user clicks on an OpenID provider link and (optionally) enters the username, the OpenID for that provider is inserted in the text field.

Below is a screenshot of our login screen after clicking the Google OpenID link:

Sign In screenshot

Final Words

While we have made a lot of progress with our login form, we haven't actually done anything to login users into our system, all we've done so far had to do with the GUI aspects of the login process. This is because before we can do real logins we need to have a database where we can record our users.

In the next chapter we will get our database up and running, and shortly after we will complete our login system, so stay tuned for the follow up articles.

The microblog application in its current state is available for download here:

Download microblog-0.3.zip.

Remember that the Flask virtual environment is not included in the zip file. For instructions on how to set it up see the first chapter of the series.

Feel free to leave comments or questions below. I hope to see you in the next chapter.

Miguel

246 comments

  • #151 Sandeep Kumar said 2014-05-31T17:41:01Z

    I followed every step but there are no links of google or other openid's on the webpage.So what might be the problem??

  • #152 Miguel Grinberg said 2014-06-01T06:01:55Z

    @Sandeep: this article deals with the form, the login functionality is implemented in a later article.

  • #153 Thomas said 2014-06-06T13:41:32Z

    Is it not possible to validate WTForms that has method="GET"?

  • #154 Miguel Grinberg said 2014-06-06T14:32:18Z

    @Thomas: you can tell Flask-WTF to validate form data from a GET request or even from JSON if you want. Just pass the dict with the data in the Form constructor. The default is to take the data from request.form.

  • #155 Andy said 2014-06-06T18:46:43Z

    Hi Miguel, awesome tutorial. I plan to go through this before going through your book (some reason it's easier to follow this than the book).

    Quick question, I'm using Python 3.3.5 on Windows, when I run run.py, it gives me an ImportError: No module named 'Forms'. So I went on stack overflow, and to resolve the error I had to import .forms instead of forms. Why can I not just import forms by itself, and how come it was possible others to do so without the period?

  • #156 Miguel Grinberg said 2014-06-07T05:49:56Z

    @Andy: The mega tutorial was written two years ago, and at that time Flask did not support Python 3. The dot in relative imports is one of the Python 3 differences, in Python 2.x you don't have to have that dot.

  • #157 nCrazed said 2014-06-12T13:37:52Z

    What is the difference between the "Required" validator that you use here and in your book, and the "DataRequired" validator used in both WTForms and Flask-WTF documentations?

  • #158 Miguel Grinberg said 2014-06-13T05:36:39Z

    @nCrazed: WTForms 2.0 deprecates Required() and instead defines DataRequired() and InputRequired(). But the current release of Flask-WTForms still uses WTForms 1.x, so that is not available yet. The differences between Required, DataRequired and InputRequired are pretty similar, DataRequired validates sanitized input, while InputRequired validates form data before it is sanitized. In WTForms 2.x the deprecated Required is an alias to DataRequired.

  • #159 Kevin said 2014-06-16T17:50:50Z

    The Javascript generating the openid is not able to handle OpenIDs in the format of .website.com. How about changing openid = openid.substr(0, u) + user ; to openid = openid.replace('', user); Thanks for the awesome tutorial

  • #160 CS said 2014-06-21T15:35:09Z

    For some reason I had to use from app.forms import LoginForm instead of from forms import LoginForm in app/views.py ps: I'm using python3.

  • #161 Mitchell said 2014-06-26T19:52:23Z

    Miguel--

    You are the kindest man on the internet. Seriously, this is excellent. I'm going through and adapting for python 3, which throws an error here or there, but I guess that's what keeps it interesting. I'm learning the details of a lot of things I've seen referenced elsewhere, but haven't had a good tutorial or explanation on, so many thanks. The database migration features are artful.

    There's some trouble above with the javascript code in the login.html template. Line endings are missing semi-colons for the cut-and-paste crowd. It's right in the zip file, though.

    Many thanks again.

  • #162 Agnaldo said 2014-07-08T18:41:09Z

    one question: why does he use the symbol | at |{% for pr in providers %} {{pr.name}} | ?

  • #163 Miguel Grinberg said 2014-07-10T03:57:55Z

    @Agnaldo: that's just a text separator, it has the cosmetic purpose to separate the different links to providers.

  • #164 michelle said 2014-07-20T15:19:01Z

    For anyone trying to use this tutorial, the shebang line does not always work as far as I can tell and that is why some of us get the import error for flask-wtf. When the shebang doesn't work, the correct python interpreter is not being used. If, like me, you cannnot get the shebang line in run.py to work, you will need to type 'flask/bin/python run.py' to get the interpreter from the virtual environment to interpret the file.

  • #165 jacob said 2014-08-05T11:00:10Z

    Hello miguel....nice work and i hav a doubt. In my login.html, it seems that control flow doesn't enter to set_openid(). ie link is not coming in textbox. Would you mind explaining the possible reasons...

  • #166 Miguel Grinberg said 2014-08-05T17:48:54Z

    @jacob: look in the javascript console, if there are any errors it will be shown there.

  • #167 Adrian Baran said 2014-08-13T17:02:00Z

    How does from_object("config") function resolves the path to the config.py file ? It is surprising for me that even if I put config.py in the tmp folder it still works.

  • #168 David Tran said 2014-08-14T04:54:36Z

    Hey Miguel, I'm really confused about the config.py file. Why is it one level above your init.py. How is python supposed to see and import it?

  • #169 Miguel Grinberg said 2014-08-15T06:26:37Z

    @David: Python finds config.py because it is in the current directory.

  • #170 Michael Wexler said 2014-09-01T19:49:49Z

    Thanks Miguel for this great tutorial. I wanted to make a small suggestion. Above you should specify where we should put the config.py file. It is a bit unclear whether or not it should be placed in the microblog directory or the app directory. Thanks :-)

  • #171 Miguel Grinberg said 2014-09-02T05:23:34Z

    @Michael: when there is any doubt, you can download the zip file at the end of the article and see how things are organized. Alternatively you can view the code directly on GitHub.

  • #172 Todd said 2014-09-24T00:42:33Z

    Hi, I am following this Tutorial and in the views.py on line 3: from forms import LoginForm I get the error ImportError: No module name 'forms'

  • #173 Miguel Grinberg said 2014-09-24T01:31:04Z

    @Todd: this tutorial was written for Python 2, I'm actually in the process it of making it work with Python 3. The correct syntax for Py3 is "from .forms import LoginForm" (note the dote before "forms").

  • #174 Ahmed Genina said 2014-10-07T00:46:19Z

    Hello Miguel Thank you so much for the awesome Tutorial and the great effort , currently am following the given steps , and am facing the following error with CSRF_ENABLED = True

    NameError:name 'True' is not defined

    could it be for a mistake from my side , or due to different versions of FLask ! Again many thanks

  • #175 Miguel Grinberg said 2014-10-08T06:10:40Z

    @Ahmed: this is a very strange error. What version of Python are you using? Can you show me the entire stack trace of the error?