Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

Flask-WTF multiple inheritance

Posted by majorasflask on 2016-07-20 @ 09:40 and filed in Forms

Ever wanted to reuse fields from multiple forms?

class BaseForm(Form):
    def __iter__(self):
        token = self.csrf_token
        yield token

        field_names = {token.name}
        for cls in self.__class__.__bases__:
            for field in cls():
                field_name = field.name
                if field_name not in field_names:
                    yield self[field_name]

        for field_name in self._fields:
            if field_name not in field_names:
                yield self[field_name]


# forms.py

class EmailForm(BaseForm):
    email = EmailField('Email')

class PasswordForm(BaseForm):
    password = PasswordField('Password')

class EmailPasswordForm(EmailForm, PasswordForm):

class NamesForm(BaseForm):
    first_name = StringField('First name')
    last_name = StringField('Last name')

class ProfileForm(EmailPasswordForm, NamesForm):
{# form.html #}

{% for field in form %}
    {{ field.label }}
    {{ field() }}
{% endfor %}

This would render the ProfileForm fields in following order:


This snippet by majorasflask can be used freely for anything you like. Consider it public domain.