ImportError: cannot import name 'db'
Asked Answered
C

1

6

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?

Condom answered 12/5, 2018 at 15:48 Comment(2)
what is the module db?Streamer
Possible duplicate of flask - blueprint - sqlalchemy - cannot import name 'db' into moles fileAntipus
N
22

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.

Novelette answered 14/5, 2018 at 18:35 Comment(1)
Thank you, that's a great answer! I think one problem I have is understanding the order that flask files are executed when you run them, in a more complex flask project like this. I'll ask a follow up question on this later.Condom

© 2022 - 2024 — McMap. All rights reserved.