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 a Flask-SQLAlchemy
model that wraps models using SQLalchemy's API. It inherits all of its models from a db
object, which I assume you are instantiating or registering inside a create_app
method.
So, you should have something like this
db = SQLAlchemy()
def create_app(config):
app = Flask(__name__)
db.init_app(app)
adm = Admin(app,name='flaskadmin')
from app.models import User
adm.add_view(ModelView(User, db.session))
return app
Whenever you import User
from user.py
you are basically importing db.Model
, which requires for db
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
File "E:\ENVS\r3\flask-base\app\models\user.py", line 7, in <module>
from .. import db, login_manager
ImportError: cannot import name 'db'
This is, in user.py
there is an import of db
from ../__init__.py
but in that file there is an import of User
happening before the definition of db
.
A db
object emulates the declarative
approach from SQLAlchemy, where the object holds data about every other Class that inherited from it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With