Updated Large app how to (markdown)

debrice 2012-02-04 11:34:13 -08:00
parent 1de9c3493e
commit c2955a3d83

@ -178,22 +178,56 @@ Now that we've done our object model, time to build the form that goes with it.
from flaskext.wtf import Form, TextField, PasswordField, BooleanField, RecaptchaField
from flaskext.wtf import Required, Email, EqualTo
class RegisterForm(Form):
class RegisterForm(Form):
name = TextField('NickName', [Required()])
email = TextField('Email address', [Required(), Email()])
password = PasswordField('Password', [
password = PasswordField('Password', [Required()])
confirm = PasswordField('Repeat Password', [
Required(),
EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS', [Required()])
repcaptcha = RecaptchaField()
The first parameters for the field is the label we'll want to display for the field. For example the name field will be labelled as NickName on the form.
The first parameters for the field is the label we'll want to display for the field. For example the name field will be labelled as NickName on the form. For the password fields, another useful validator got used here, EqualTo, it compares the data contained in the current field with the data of the other specified field.
Form more details of what can be done with WTF check [http://wtforms.simplecodes.com/docs/dev/]
### First view
The view is where we'll declare our Blueprint. Using url_prefix will prefix every url you set using route. A nice feature from WTF-Flask is the form.validate_on_submit: it check that the current request is POST and that the form validates.
from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for
from werkzeug import check_password_hash, generate_password_hash
from app import db
from app.users.forms import RegisterForm
from app.users.models import User
mod = Blueprint('user', __name__, url_prefix='/users')
@mod.route('/me/')
def home():
# dummy view just displaying hello
return "Hello"
@mod.route('/register/', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if form.validate_on_submit():
# create a user instance not yet stored in the database
user = User(form.name.data, form.email.data, \
generate_password_hash(form.password.data))
# Insert the record in our database and commit it
db.session.add(user)
db.session.commit()
# Log user in, as user know has an id
session['user_id'] = user.id
# flash will had a message to be displayed to the user
flash('Thanks for registering')
# redirect user to the 'home' method of the user module.
return redirect(url_for('user.home'))
return render_template("users/register.html", form=form)