Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

python - Tyring to set up modelview with Flask-Admin causes ImportError

I am trying to add a User model view to Flask-Admin. However, I get ImportError: cannot import name db. Why is this happening and how do I fix it?

app/__init__.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import flask_admin as admin
from app.models import User

db = SQLAlchemy()
admin = admin.Admin(name="Admin Panel")

def create_app(config_name):
    app = Flask(__name__)
    db.init_app(app)
    admin.init_app(app)
    admin.add_view(ModelView(User, db.session))
    return app

app/models.py:

from . import db, login_manager

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)

When I add admin.add_view(ModelView(User, db.session)), I have to add from app.models import User as well. I get this error after adding these lines:

Traceback (most recent call last):
      File "manage.py", line 3, in <module>
        from app.models import User, Role
      File "/home/qadim/PycharmProjects/esouq/app/__init__.py", line 1, in <module>
        from app.models import User
      File "/home/qadim/PycharmProjects/esouq/app/models.py", line 9, in <module>
        from . import db, login_manager
    ImportError: cannot import name db
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code has the line from app.models import User in __init__.py. The problem is that app.models has from . import db. This is a circular import: __init__ tries to import User, which tries to import db, which isn't defined until after __init__ tries to import User. To solve this, move your local app imports below the definitions of all the global extension stuff.

Currently, your code looks something like:

from flask_sqlalchemy import SQLAlchemy
from app.models import User

db = SQLAlchemy()

You need to change it to:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

from app.models import User

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...