[英]how set session for wtforms-alchemy when I using flask-sqlalchemy?
I`m using flask-sqlalchemy and init SQLAlchemy() in my application by init_app() like this : 我正在通过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)
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 : 现在,当我在form.py中使用wtforms-alchemy时,如下所示:
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 : 在WTForms-Alchemy高级部分中 :
In order to make WTForms-Alchemy work with Flask-WTF you need the following snippet:
为了使WTForms-Alchemy与Flask-WTF配合使用,您需要以下代码段:
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:
您可以像之前一样使用ModelForm:
class UserForm(ModelForm): class Meta: model = User
This does rely on User
having a .query
object; 这确实依赖于
User
具有.query
对象; eg your User
model must be derived from db.Model
. 例如,您的
User
模型必须从db.Model
派生。 If it doesn't then you need to define get_session
method on the form : 如果不是,那么您需要在表单上定义
get_session
方法:
class UserForm(ModelForm):
class Meta:
model = User
def get_session(self):
return db.session
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.