我正在尝试在我的管理页面中的某个 ModelView 上加载脚本:
class CustomView(ModelView):
# Neither approach works here:
# with current_app.app_context(), current_app.test_request_context():
extra_js = [url_for('static', filename='admin/admin.js')]
Run Code Online (Sandbox Code Playgroud)
随着app_context()注释掉,我得到这个错误:
运行时错误:尝试在没有推送应用程序上下文的情况下生成 URL。这必须在应用程序上下文可用时执行。
取消注释 app_context 会给我这个错误:
运行时错误:在应用程序上下文之外工作。这通常意味着您尝试使用需要以某种方式与当前应用程序对象交互的功能。要解决此问题,请使用 app.app_context() 设置应用程序上下文。有关更多信息,请参阅文档。
我还尝试在设置管理视图时添加上下文,但得到相同的错误:
# ADMIN
with app.app_context():
admin = Admin(app, name='Custom', template_mode='bootstrap3', index_view=MyIndex(), base_template='admin/base.html')
admin.add_view(CustomView(User, db.session))
Run Code Online (Sandbox Code Playgroud)
那么,我如何适当地传递应用程序上下文来加载我的这个视图的脚本?
我找到了一个解决方案,我不确定它是否能完美满足您的需求,但只要我通过谷歌搜索我的问题对这个话题有感觉,我希望这可以帮助其他人。
因此,为了使url_for在flask admin extra_js属性中可用,我只是在我的类中定义了我的extra_js属性,该属性通过覆盖render 方法实现了flask admin 的ModelView基类.. 片段等于数千个单词:
class MyModelView(AdminModelView):
def render(self, template, **kwargs):
"""
using extra js in render method allow use
url_for that itself requires an app context
"""
self.extra_js = [url_for("static", filename="js/whatever.js")]
return super(MyModelView, self).render(template, **kwargs)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助 !