---
title: Flask Day 2
date: 2016-02-16 22:45:06
---

To handle web forms we use [Flask-WTF	](http://packages.python.org/Flask-WTF). So we need to write a config file (file `config.py`):

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

And then you need to use this config (file `app/__init__.py`):

``` python
from flask import Flask

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

from app import views
```

Let's build a simple form (file `app/forms.app`):

``` python
from flask.ext.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)
```

The `DataRequired()` is a validator that checks the field is empty or not.

After that, we need a HTML page to show the form (file `app/templates/login.html`):

``` 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 %}
```



The final step is to code a view function that renders the template and receiving data from form (file `app/views.py`):

``` python
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()
    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)
```

