WTForms-Alchemy

raw JSON →
0.19.1 verified Mon Apr 27 auth: no python

Generates WTForms forms from SQLAlchemy models, reducing boilerplate for Flask and other web frameworks. Current version 0.19.1, with irregular releases.

pip install wtforms-alchemy
error wtforms_alchemy.exceptions.UnknownTypeException: Unknown column type: <class 'sqlalchemy.dialects.postgresql.ARRAY'>
cause The column type is not registered in the default type mapping.
fix
Add a type mapping in the Meta class: 'type_mapping = {ARRAY: StringField}' or similar.
error AttributeError: 'ModelForm' object has no attribute 'validate_unique'
cause UniqueValidator is not automatically added; you need to enable it explicitly.
fix
Set 'validators = [UniqueValidator()]' on the field or use 'include_unique' in Meta.
error ImportError: cannot import name 'ModelForm' from 'wtforms_alchemy'
cause Old versions may have different import paths; ensure version >=0.16.0 or install from PyPI.
fix
Upgrade to latest version with 'pip install --upgrade wtforms-alchemy'.
breaking In version 0.19.0, support for SQLAlchemy 1.x was dropped; SQLAlchemy 2.0+ is required.
fix Upgrade SQLAlchemy to 2.0+ or pin wtforms-alchemy to <0.19.0.
deprecated The 'inline_models' feature is deprecated and will be removed in a future version.
fix Use ModelFormField for nested forms instead.
gotcha Auto-generated field types depend on column type mapping; unhandled types raise ValueError. Ensure all model columns map to known WTForms fields.
fix Register custom type mapping using 'type_mapping' in Meta class.
gotcha Unique validation requires a SQLAlchemy session to be passed explicitly via Meta's 'session' attribute or set globally.
fix Add 'session = session' to Meta class or call init with session=session.

Generate a WTForms form from a SQLAlchemy model.

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from wtforms_alchemy import ModelForm

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False)
    email = Column(String(100), nullable=False)

engine = create_engine('sqlite:///')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

class UserForm(ModelForm):
    class Meta:
        model = User
        include = ['name', 'email']

form = UserForm()
print(form.name.label.text)