Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: cannot import name 'db'

enter image description here

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))

enter image description here

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?

like image 473
user1592380 Avatar asked May 12 '18 15:05

user1592380


1 Answers

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.

like image 152
bluesmonk Avatar answered Oct 09 '22 15:10

bluesmonk