问题 将参数传递给flask-admin中的ModelView编辑模板


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

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

我无法弄清楚如何将参数传递给我的edit.html模板。

这是代码:

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

从flask-admin的文档我发现了 _template_args 可用于将参数传递给模板。但我无法弄清楚如何。

这样做的确切方法是什么?


4391
2017-12-20 17:49


起源



答案:


您必须覆盖要更改的视图 _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()

如果要将某些全局值传递给模板,可以使用a 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')

14
2017-12-21 00:55



我正在尝试使用index_view做类似的事情,但它根本不起作用。我一直得到异常:异常:尝试实例化管理视图UserModelView没有默认视图任何想法有什么问题? - James Hush
@JamieHush不知道,我不禁没有一些代码。如果你是子类,它应该工作 AdminIndexView 和覆盖 index 功能。 - iurisilvio
AttributeError:'super'对象没有属性'index' - jul
@jul这个答案有点老了,也许Flask-Admin改变了一些实现细节。我真的不知道为什么这段代码会调用 index() 代替 edit_view()。我会更新我的答案。 - iurisilvio
我猜 super(TestAdmin, self).edit_view() 也应该归还。 - jul


答案:


您必须覆盖要更改的视图 _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()

如果要将某些全局值传递给模板,可以使用a 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')

14
2017-12-21 00:55



我正在尝试使用index_view做类似的事情,但它根本不起作用。我一直得到异常:异常:尝试实例化管理视图UserModelView没有默认视图任何想法有什么问题? - James Hush
@JamieHush不知道,我不禁没有一些代码。如果你是子类,它应该工作 AdminIndexView 和覆盖 index 功能。 - iurisilvio
AttributeError:'super'对象没有属性'index' - jul
@jul这个答案有点老了,也许Flask-Admin改变了一些实现细节。我真的不知道为什么这段代码会调用 index() 代替 edit_view()。我会更新我的答案。 - iurisilvio
我猜 super(TestAdmin, self).edit_view() 也应该归还。 - jul