【问题标题】:Passing Arguments to ModelView edit template in flask-admin在 flask-admin 中将参数传递给 ModelView 编辑模板
【发布时间】:2013-12-20 17:49:48
【问题描述】:

我正在尝试通过构建 CMS 来了解有关 Flask 的更多信息。我正在使用 flask-admin 来添加帖子、图片等。

我已经设法用ckeditor 覆盖了textarea。但我想将静态文件夹中图像的路径传递给ckeditor图像插件。

我不知道如何将参数传递给我的 edit.html 模板。

代码如下:

class TestAdmin(ModelView):
    form_overrides = dict(text=forms.CustomTextAreaField)
    create_template = 'edit.html'
    edit_template = 'edit.html'

从flask-admin 的文档中我发现_template_args 可以用来将参数传递给模板。但我不知道怎么做。

具体的方法是什么?

【问题讨论】:

    标签: python flask flask-admin


    【解决方案1】:

    您必须覆盖视图才能更改_template_args

    class TestAdmin(ModelView):
        form_overrides = dict(text=forms.CustomTextAreaField)
        create_template = 'edit.html'
        edit_template = 'edit.html'
    
        @expose('/edit/', methods=('GET', 'POST'))
        def edit_view(self):
             self._template_args['foo'] = 'bar'
             return super(TestAdmin, self).edit_view()
    

    如果您想将一些全局值传递给模板,您可以使用context_processor (http://flask.pocoo.org/docs/templating/#context-processors)。

    @app.context_processor
    def inject_paths():
        # you will be able to access {{ path1 }} and {{ path2 }} in templates
        return dict(path1='x', path2='y')
    

    【讨论】:

    • 我正在尝试用 index_view 做类似的事情,但它根本不起作用。我不断收到异常:异常:尝试在没有默认视图的情况下实例化管理视图 UserModelView 知道有什么问题吗?
    • @JamieHush 不知道,没有一些代码我无能为力。如果您继承 AdminIndexView 并覆盖 index 函数,它应该可以工作。
    • AttributeError: 'super' object has no attribute 'index'
    • @jul 这个答案有点老了,也许 Flask-Admin 改变了一些实现细节。我真的不知道为什么这段代码调用index() 而不是edit_view()。我会更新我的答案。
    • 我猜super(TestAdmin, self).edit_view() 也应该返回。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    相关资源
    最近更新 更多