gpt4 book ai didi

flask 管理员 : extra_js and url_for

转载 作者:行者123 更新时间:2023-12-03 21:23:34 35 4
gpt4 key购买 nike

我正在尝试在我的管理页面中的某个 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_context()注释掉,我收到此错误:

RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.



取消注释 app_context 会给我这个错误:

RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context(). See the documentation for more information.



我还尝试在设置管理 View 时添加上下文,但得到相同的错误:
# 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))

那么,我如何适本地传递应用程序上下文来加载我的这个 View 的脚本?

最佳答案

我找到了一个解决方案,我不确定它是否能完美满足您的需求,但只要我通过谷歌搜索我的问题对这个话题有感觉,我希望这可以帮助其他人。

所以,为了使 url_for 在 flask 管理员中可用 extra_js 属性,我刚刚定义了我的 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)

希望这可以帮助 !

关于 flask 管理员 : extra_js and url_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50531796/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com