CheckboxSelectMultiple呈酥脆形式,自定义数据属性

时间:2020-07-23 16:39:09

标签: django django-crispy-forms

我想覆盖CheckboxSelectMultiple,以便可以使用以下逻辑将数据属性赋予表单:

class MySelect(forms.Select):

    def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
        option = super(forms.Select, self).create_option(name, value, label, selected, index, subindex, attrs)
        if value:
            for k,attr in self.attrs.items():
                # if it has a data attr in it
                if k[:4] == 'data':
                    #instantiate a new object and add the data attr to the option
                    current_object = self.choices.queryset.model.objects.get(pk=value)
                    option['attrs'].update({
                        k: getattr(current_object, attr)
                    })
        return option

这对于非脆皮表格效果很好,但是由于crispy从未调用此方法,因此它将无法采用这种方式。我想覆盖CheckboxSelectMultiple create_option方法。 有什么绝妙的方法可以解决此问题,而不必覆盖整个表单字段呈现过程? 我尝试使用自定义html,但是(就我的技能而言)它是如此复杂,以使其具有选中属性可以正常工作的CheckboxSelectMultiple。

这是我到目前为止所做的:

class MyCheckboxSelectMultiple(forms.CheckboxSelectMultiple):

    def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
        option = super(forms.CheckboxSelectMultiple, self).create_option(name, value, label, selected, index, subindex, attrs)
        if value:
            for k,attr in self.attrs.items():
                # if it has a data attr in it
                if k[:4] == 'data':
                    #instantiate a new object and add the data attr to the option
                    current_object = self.choices.queryset.model.objects.get(pk=value)
                    option['attrs'].update({
                        k: getattr(current_object, attr)
                    })
        return option

0 个答案:

没有答案