python - ChoiceFieldRenderer 已删除。解决办法是什么?

标签 python django

好像很少人用过,但是……我用过。 Here你可以阅读:

Some undocumented classes in django.forms.widgets are removed: SubWidget RendererMixin, ChoiceFieldRenderer, RadioFieldRenderer, CheckboxFieldRenderer ChoiceInput, RadioChoiceInput, CheckboxChoiceInput

我的源代码是:

from django.forms.widgets import ChoiceFieldRenderer, RadioChoiceInput, \
    RendererMixin, Select


class BootstrapRadioFieldRenderer(ChoiceFieldRenderer):
    outer_html = '<span {id_attr}>{content}</span>'
    inner_html = '<div class="radio">{choice_value}{sub_widgets}</div>'
    choice_input_class = RadioChoiceInput


class BootstrapRadioSelect(RendererMixin, Select):
    renderer = BootstrapRadioFieldRenderer
    _empty_value = ''

我真的不知道如何转换它以使其适用于 1.11 及更高版本:他们说:

Use a custom widget template instead.

嗯。怎么办?

最佳答案

我们使用 RadioFieldRenderer 为每个选项添加描述。您的用例可能远非如此,但我希望它也能帮助您进行迁移。

这是 Django <=1.10 的遗留代码

class MyRadioFieldRenderer(forms.widgets.RadioFieldRenderer):

    def render(self):
        radios = []
        for w in self:
            radios.append(u"""<li class="%s">%s <span>%s</span></li>"""
                          % (w.choice_value, force_unicode(w), get_description(w)))
        return mark_safe(u'<ul>\n%s\n</ul>' % u'\n'.join(radios))

class MyRadioSelect(forms.RadioSelect):
    renderer = MyRadioFieldRenderer

对于 Django 1.11,我使用自定义模板片段将其替换为这个,并且只将描述添加到模板上下文中。

from django.forms.widgets import RadioSelect

class MyRadioSelect(RadioSelect):

    template_name = 'myapp/multiple_input.html'
    option_template_name = 'myapp/input_option.html'

    def get_context(self, name, value, attrs):
        context = super(MyRadioSelect, self).get_context(name, value, attrs)

        for i in range(len(context['widget']['optgroups'][0][1])):
            value = context['widget']['optgroups'][0][1][i]['value']
            context['widget']['optgroups'][0][1][i]['attrs']['description'] = \
                get_description(value)
        return context

这个深列表中的 for 循环并不漂亮。需要再看一遍。

然后在模板片段中,我可以使用 <span>{{widget.attrs.description | safe}}</span> 呈现选项后面的描述。

形式保持不变:

class MyForm(forms.Form):

    order_method = ChoiceField(
        widget=MyRadioSelect,
        required=True)

重要:要让 Django 在常规模板文件夹中找到您的自定义模板片段,请将其添加到您的设置中:

FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'

django.forms给你的INSTALLED_APPS

关于python - ChoiceFieldRenderer 已删除。解决办法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46517799/

相关文章:

python - 如何在 Django 中建立 "One or Many"关系模型?

python - 如何重载类成员的分配?

python - Scrapy 安装在 Ubuntu : pkg_resources. DistributionNotFound: attrs

python - 如何从 django 前端定时安排任务?

python - 使用 Pandas 数据框中的列作为查找来选择同一 df 中的第二列两次,然后对结果进行比较

python - 无法更新 python-netsnmpagent 中的表条目

python - Django:Gmail SMTP 错误:请先运行 connect()

python - 使用 QuerySet 的 Django 子查询

python - 使用 Python Ctypes 加载 dll

python - 无法在 Django 中使用 AJAX POST