How do I properly set up flask-admin views with using an application factory?

怎甘沉沦 提交于 2019-12-04 16:34:18

Well, this is old, but here is how I do it:

# Inside app/auth/__init__.py (auth module includes admin):

#...
from app import db
from flask import Blueprint
from .my_custom_model_views import MyModelView
from ..models import MyModel
#...
auth = Blueprint('auth', __name__)
from . import views
#...
auth.custom_model_views = []
auth.custom_model_views += [MyModelView(MyModel, db.session)]
#...
from . import forms

# Inside app/__init__.py
# ...
admin = Admin(name='Name', ...)
# ...
def create_app(config_name):
# ...
    app = Flask(__name__)
    # ...
    admin.init_app(app)
    # And here's the important part
    with app.app_context():
        from .auth import auth as auth_blueprint
        admin.add_views(*auth_blueprint.custom_model_views)

The important part is somehow storing the views you want to add (here, I just attach them to the Blueprint) and then adding them WITH APP CONTEXT. Otherwise, everything goes berserk (without app context, it is possible to add the same model multiple times, resulting in ugly name collision errors during instantiation of the app).

It's worth noting that any views you add here will show up in the flask admin menu as if it were a model view, even if it is some other kind of view. You can fix this by changing the view's is_visible and is_accessible methods.

Here is another way using blueprints:

# app/__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin

db = SQLAlchemy()
admin = Admin(name='my-app', template_mode='bootstrap3')


def create_app():
    app = Flask(__name__)

    db.init_app(app)
    admin.init_app(app)

    # Add the admin panel
    from app.admin import bp as admin_bp
    app.register_blueprint(admin_bp)

    return app
# app/admin/__init__.py

from flask import Blueprint

bp = Blueprint('admin_bp', __name__)

from app.admin import routes
# app/admin/routes.py

from flask_admin.contrib.sqla import ModelView
from app import db, admin
from app.models import City

admin.add_view(ModelView(City, db.session))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!