File: advanced.rst

package info (click to toggle)
wtforms-alchemy 0.19.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 492 kB
  • sloc: python: 3,955; makefile: 119; sh: 11
file content (72 lines) | stat: -rw-r--r-- 1,750 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
Advanced concepts
=================

Using WTForms-Alchemy with SQLAlchemy-Defaults
----------------------------------------------

WTForms-Alchemy works wonderfully with `SQLAlchemy-Defaults`_. When using `SQLAlchemy-Defaults`_ with WTForms-Alchemy you
can define your models and model forms with much more robust syntax. For more information see `SQLAlchemy-Defaults`_ documentation.


.. _SQLAlchemy-Defaults: https://github.com/kvesteri/sqlalchemy-defaults


Example ::

    from sqlalchemy_defaults import LazyConfigured


    class User(Base, LazyConfigured):
        __tablename__ = 'user'
        id = sa.Column(sa.Integer, primary_key=True)
        name = sa.Column(
            sa.Unicode(255),
            nullable=False,
            label=u'Name'
        )
        age = sa.Column(
            sa.Integer,
            nullable=False,
            min=18,
            max=100,
            label=u'Age'
        )


    class UserForm(ModelForm):
        class Meta:
            model = User


Using WTForms-Alchemy with Flask-WTF
------------------------------------

In order to make WTForms-Alchemy work with `Flask-WTF`_ you need the following snippet:

.. _Flask-WTF: https://github.com/lepture/flask-wtf/

::


    from flask_wtf import FlaskForm
    from wtforms_alchemy import model_form_factory
    # The variable db here is a SQLAlchemy object instance from
    # Flask-SQLAlchemy package
    from myproject.extensions import db

    BaseModelForm = model_form_factory(FlaskForm)

    class ModelForm(BaseModelForm):
        @classmethod
        def get_session(self):
            return db.session

Then you can use the ModelForm just like before:


::


    class UserForm(ModelForm):
        class Meta:
            model = User