所以我只是将我的小应用程序迁移到了定义了两个蓝图的蓝图。
我收到此错误:ImportError: cannot import name User
我不知道这里出了什么问题。我相信没有循环导入,或者是否与它有什么关系。我对Python和编程都很陌生。
此外,如果我将core.py导入行更改为:from users.models import *
,它将一直有效,直到我加载网页,然后我得到一个回溯,说'全局名称用户未定义'。对于users \ views.py导入行也是如此。
我尝试导入它的唯一两个地方就在这里;
core.py:
from flask import Flask, g
from flask_sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, current_user
from flask.ext.bcrypt import Bcrypt
from assets.forms import SearchAssetTag
app = Flask(__name__)
app.config.from_object('config')
login_manager = LoginManager()
login_manager.init_app(app)
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
from users.models import User
@login_manager.user_loader
def load_user(user_id):
return User.query.filter(User.id == int(user_id)).first()
#Define headersearchform globally as it runs on every page with header.
@app.before_request
def before_request():
g.headersearchform = SearchAssetTag()
g.current_user = current_user
from users.views import users_blueprint
from assets.views import assets_blueprint
app.register_blueprint(users_blueprint)
app.register_blueprint(assets_blueprint)
在 /users/views.py 中,我显然必须引用用户对象进行登录以及诸如此类的内容;
from flask import render_template, request, session, url_for, redirect, flash, Blueprint
from core import app, db
from sqlalchemy.exc import IntegrityError
from forms import SignupForm, LoginForm
from models import User
from flask.ext.login import login_user, login_required, current_user, logout_user
users_blueprint = Blueprint('users', __name__, template_folder = 'templates')
文件夹结构如下所示;
core.py
__init__.py
config.py
\users
__init__.py
views.py
forms.py
models.py
\templates
template.html
\assets
__init__.py
views.py
forms.py
models.py
\templates
template.html
最后,这是 model.py 文件,其中为SQLAlchemy定义了User类:
from core import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String, nullable=False)
last_name = db.Column(db.String, nullable=False)
email = db.Column(db.String, nullable=False)
title = db.Column(db.String, nullable=False)
password = db.Column(db.String)
def __init__(self, first_name, last_name, email, title, password):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.title = title
self.password = bcrypt.generate_password_hash(password)
答案 0 :(得分:3)
models.py
正在从核心导入db
,而core.py
正在从模型中导入User
你应该移动这一行:
from users.models import User
到core.py
的底部。这种情况当models.py
尝试从db
导入core
时,它将被定义(因为它已超过该点)
答案 1 :(得分:0)
当您从Django版本2及更高版本的.models中导入用户时,此方法有效