Flask Admin:extra_js和url_用于
我正在尝试在我的管理页面中的某个ModelView上加载脚本:Flask Admin:extra_js和url_用于,flask,flask-admin,Flask,Flask Admin,我正在尝试在我的管理页面中的某个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')] 注释掉app\u context(
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')]
注释掉app\u context()
后,出现以下错误:
RuntimeError:尝试在没有应用程序的情况下生成URL
上下文被推送。这必须在应用程序上下文中执行
有空
取消对app_上下文的注释会导致以下错误:
运行时错误:在应用程序上下文之外工作。这通常是
表示您试图使用接口所需的功能
以某种方式使用当前应用程序对象。要解决此问题,请设置
具有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))
那么,我如何才能适当地传递应用程序上下文以加载此视图的脚本呢?我找到了一个解决方案,我不确定它是否完全满足您的需要,但只要我通过谷歌搜索我的问题来了解这个主题,我希望这能对同事有所帮助 因此,为了使flask adminextra_js属性中的url\u可用,我刚刚在类中定义了我的extra_js属性,该属性通过重写呈现方法来实现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)
希望这有帮助 谢谢,这很有帮助!只是为了指出其他的问题。AdminModelView只是常规的ModelView类,这首先让我感到困惑。