BlocNotes

Notepad of a tinker, maker, hacker or whatever you call it :)

Flask-Security - How to extend a form and the validator

I am currently building a Python application, which let me use:

  • Flask - a simple and very well documented web Framework
  • Flask-Security - an extension dedicated to user management.
    While it is a really great extension, there is some documentation missing or quite hard to find on search engines or StackOverflow.

How to add fields to a Flask's security form, with custom validator.

First, we need to declare a new class, which extends RegisterForm, then add the new fields we want on the form.
If we want a custom validator for that field, we need to define it, but in order to avoid losing Flask-Security validator, just call it with Form.validate(self)
The last thing needed is to tell Flask-Security to use our form when instantiate it.

Instantiation

security = Security(app, user_datastore, register_form=ExtendedRegisterForm)  

Form.py

from flask.ext.wtf import Form  
from wtforms import StringField, BooleanField  
from wtforms.validators import DataRequired  
from flask_security.forms import RegisterForm  
from .models import User


class ExtendedRegisterForm(RegisterForm):  
    """ Add nickname field to the register's class
    """
    nickname = StringField('Nickname', [DataRequired()])

    def validate(self):
        """ Add nicknae validation

            :return: True is the form is valid
        """
        # Use standart validator
        validation = Form.validate(self)
        if not validation:
            return False

        # Check if nickname already exists       
        user = User.query.filter_by(
            nickname=self.nickname.data).first()
        if user is not None:
            # Text displayed to the user
            self.nickname.errors.append('Nickname already exists')
            return False

        return True

And you are done !