I am working on adding flask admin to a preexisting flask boiler plate project. I've been able to get the basic project working at https://github.com/kc1/flask-base (SCREENSHOT). I now need to add modelviews to add basic CRUD functionality. To do this I changed the code to :
adm = Admin(app,name='flaskadmin')
from app.models import User
adm.add_view(ModelView(User, db.session))
You can see that it works. But if I import the User model with the rest of the imports at the top of app/init I get:
Traceback (most recent call last):
File "...flask-base/manage.py", line 10, in <module>
from app import create_app, db
File "E:\ENVS\r3\flask-base\app\__init__.py", line 17, in <module>
from app.models import User
File "E:\ENVS\r3\flask-base\app\models\__init__.py", line 6, in <module>
from .user import * # noqa
File "E:\ENVS\r3\flask-base\app\models\user.py", line 7, in <module>
from .. import db, login_manager
ImportError: cannot import name 'db'
Why?
User
is aFlask-SQLAlchemy
model that wraps models using SQLalchemy's API. It inherits all of its models from adb
object, which I assume you are instantiating or registering inside acreate_app
method.So, you should have something like this
Whenever you import
User
fromuser.py
you are basically importingdb.Model
, which requires fordb
to exists and actually contain data. Be wary of circular imports in Flask and in Python in general.The error you are receiving is clearly stated in the error traceback
This is, in
user.py
there is an import ofdb
from../__init__.py
but in that file there is an import ofUser
happening before the definition ofdb
.A
db
object emulates thedeclarative
approach from SQLAlchemy, where the object holds data about every other Class that inherited from it.