我在init_app()的应用程序中使用flask-sqlalchemy和init SQLAlchemy(),如下所示:
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)
我的模特是:
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
现在当我在form.py中使用wtforms-alchemy时:
from wtforms_alchemy import ModelForm
class UserForm(ModelForm):
class Meta:
model = User
我有这个错误:
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.
我该如何修复这个错误?
答案 0 :(得分:1)
来自WTForms-Alchemy advanced section:
为了让WTForms-Alchemy与Flask-WTF合作,您需要以下代码段:
from flask.ext.wtf import Form from wtforms_alchemy import model_form_factory ModelForm = model_form_factory(Form)
您可以像以前一样使用ModelForm:
class UserForm(ModelForm): class Meta: model = User
此确实依赖User
拥有.query
个对象;例如您的User
模型必须来自db.Model
。如果它没有,那么您需要在表单上定义get_session
方法:
class UserForm(ModelForm):
class Meta:
model = User
def get_session(self):
return db.session