Django小部件覆盖模板 [英] Django widget override template

查看:74
本文介绍了Django小部件覆盖模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是django的新朋友。

I am new at django.

我想创建一个自定义小部件。

I want to create a custom widget.

forms.py:

from project.widgets import MultiChoiceFilterWidget

class CustomSearchForm(FacetedSearchForm):
    TEST_COLORS = [
        u"Blau", u"Rot", u"Gelb"
    ]

    color = forms.MultipleChoiceField(
        label=_("Color"), choices=[(x, x) for x in TEST_COLORS],
        widget=MultiChoiceFilterWidget, required=False)

widget.py:

widget.py:

class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple):
    template_name = 'project/widgets/filter.html'
    option_template_name = 'ptoject/widgets/filter_option.html'

project / widgets / filter.html:

project/widgets/filter.html:

 <h1>TEST</h1>

但是它不会渲染新模板,而是仍然渲染旧模板。

But it doesn't render the new template, instead it still renders the old way.

能给我一些提示吗?

推荐答案

Django版本< 1.11:

窗口小部件必须实现 render 方法,以便呈现不同的模板:

The widget must implement the render method in order to render a different template:

from django.utils.safestring import mark_safe
from django.template.loader import render_to_string

class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple):
    template_name = 'project/widgets/filter.html'

    def render(self, data):
        ...
        Do stuff with data
        ...
        return mark_safe(render_to_string(self.template_name))



Django版本1.11:

渲染器的文档,我们可以找到以下内容:

In the renderer's documentation, we can find the following:

Django 1.11的新功能:

New in Django 1.11:

在旧版本中,小部件使用Python渲染。本文档中描述的所有API都是新的。

In older versions, widgets are rendered using Python. All APIs described in this document are new.

并查看小工具源代码,尤其是关于输入小部件扩展了 Widget 类,我们可以看到您只需要按以下方式自定义小部件:

And by having a look at the widget source code and specifically on how the Input widget extends the Widget class, we can see that you would only need to customize your widget as follows:

class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple):
    template_name = 'project/widgets/filter.html'

您已经拥有了。

这篇关于Django小部件覆盖模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆