Вопрос

I`m using flask-sqlalchemy and init SQLAlchemy() in my application by init_app() like this :

in config file :

SQLALCHEMY_DATABASE_URI = 'sqlite:///example.db'
---------------------    
in extension file :

from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()
---------------------
in application file: 

#in my application file that generate my app
from ----- import db 

db.init_app(app)

my model is :

from -------- import db

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, autoincrement=True , primary_key=True)
    username = db.Column(db.String(50),unique=True)
    password = db.Column(db.String(50))
    email = db.Column(db.String(50),unique=True)

    def __repr__(self):
        return '<User %r>' % self.username

now when i using wtforms-alchemy in my form.py like this :

from wtforms_alchemy import ModelForm

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

i have this error :

File "/usr/local/lib/python2.7/dist-packages/wtforms_components/validators.py", line 220, in _check_for_session
raise Exception('Could not obtain SQLAlchemy session.')

Exception: Could not obtain SQLAlchemy session.

How can i fix this bug ?

Это было полезно?

Решение

From the WTForms-Alchemy advanced section:

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

from flask.ext.wtf import Form
from wtforms_alchemy import model_form_factory

ModelForm = model_form_factory(Form)

The you can use the ModelForm just like before:

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

This does rely on User having a .query object; e.g. your User model must be derived from db.Model. If it doesn't then you need to define get_session method on the form:

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

    def get_session(self):
        return db.session
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top