0

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 ?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanx about your answer but my problem is sqlalchemy session.
@sdnaghdi: all that WTForms-Alchemy Unique validators do is look for User.query; if that doesn't exist then you need to add a get_session() method. It most likely means that you didn't use db.Model for your User model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.