RadioSelect小部件在MultiWidget中不显示标签

时间:2018-06-29 22:27:57

标签: django django-models django-forms

我正在尝试在Django中构建一个自定义MultiValue字段,该字段包含两个小部件:RadioSelect和TextInput:如果用户选择“其他”,则可以在其中插入值。

一切正常,只有一个奇怪的例外:单选按钮的标签未显示(见图)。值可以正常显示,但标签不存在。我在做什么错了?

screen_shot_multi_value

fields.py

from .widgets import OtherSelectorWidget

class OtherModelField(models.CharField):
    def __init__(self, *args, **kwargs):
        self.inner_choices = kwargs.pop('choices', None)
        super().__init__(*args, **kwargs)

    def formfield(self, **kwargs):
        return OtherFormField(choices=self.inner_choices, **kwargs)


class OtherFormField(MultiValueField):
    def __init__(self, **kwargs):
        self.choices = kwargs.pop('choices')
        self.widget = OtherSelectorWidget(choices=self.choices)
        fields = (CharField(), CharField(),)
        super().__init__(fields=fields, require_all_fields=False, **kwargs)

    def compress(self, data_list):
        return str(data_list)

widgets.py

from datetime import date
from django.forms import widgets


class OtherSelectorWidget(widgets.MultiWidget):
    def __init__(self, choices=None, attrs=None):
        self.choices = choices
        _widgets = (
            widgets.RadioSelect(choices=choices),
            widgets.TextInput(attrs=attrs),
        )
        super().__init__(_widgets, attrs)

    def decompress(self, value):
        if value:
            return [value[0], value[1]]
        return [None, None, ]

    def format_output(self, rendered_widgets):

        return ''.join(rendered_widgets)

    def value_from_datadict(self, data, files, name):
        datelist = [
            widget.value_from_datadict(data, files, name + '_%s' % i)
            for i, widget in enumerate(self.widgets)]

        radio_data = self.widgets[0].value_from_datadict(data, files, name + '_0')
        text_data = self.widgets[1].value_from_datadict(data, files, name + '_1')
        try:
            D = [radio_data, text_data]
        except ValueError:
            return ''
        else:
            return D

1 个答案:

答案 0 :(得分:2)

在Django中似乎是一个小故障。这是票证的链接:https://code.djangoproject.com/ticket/29200

我通过在小部件的上下文中添加wrap_label来解决它:

class OtherSelectorWidget(widgets.MultiWidget):

    def get_context(self, name, value, attrs):
        con = super().get_context(name, value, attrs)
        con['wrap_label'] = True
        return con

然后一切都正确呈现