Skip to content

Instantly share code, notes, and snippets.

@gonz
Created December 7, 2012 19:09
Show Gist options
  • Save gonz/4235626 to your computer and use it in GitHub Desktop.
Save gonz/4235626 to your computer and use it in GitHub Desktop.
wtform
from flask.ext.wtf import (Form, TextField, PasswordField, Required,
Email, BooleanField, EqualTo)
from prism.models.user import User
from sqlalchemy import or_
class RegistrationForm(Form):
username = TextField('Username',
validators=[Required()])
password = PasswordField('Password', validators=[Required()])
password_confirm = PasswordField(
'Password confirmation',
validators=[Required(),
EqualTo('password', message="Passwords don't match")])
email = TextField('E-mail', validators=[Required(), Email()])
def validate(self):
is_valid = Form.validate(self)
errors = {}
# Validate fields are not already taken.
unique_fields = ('username', 'email')
message = '%s already taken.'
clauses = {field: getattr(User, field) == getattr(self, field).data
for field in unique_fields if field not in self.errors}
if clauses:
users = User.query.filter(or_(*clauses.values())).all()
errors = {field: message % getattr(self, field).label.text
for user in users for field in clauses.keys()
if getattr(user, field) == getattr(self, field).data}
self.errors.update(errors)
return is_valid and not errors
from flask.ext.wtf import (Form, TextField, PasswordField, Required,
Email, BooleanField, EqualTo)
from prism.models.user import User
from sqlalchemy import or_
class RegistrationForm(Form):
username = TextField('Username',
validators=[Required()])
password = PasswordField('Password', validators=[Required()])
password_confirm = PasswordField(
'Password confirmation',
validators=[Required(),
EqualTo('password', message="Passwords don't match")])
email = TextField('E-mail', validators=[Required(), Email()])
def validate(self):
if not Form.validate(self):
return False
users = User.query.filter(User.email==self.email.data |
User.username==self.username.data).all()
if self.email.data in [u.email for u in users]:
self.errors['email'] = 'Email already registered.'
if self.username.data in [u.username for u in users]:
self.errors['username'] = 'Username already taken.'
return not self.errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment