Django 复选框选择crispy forms中的Multiple,自定义数据属性

Django 复选框选择crispy forms中的Multiple,自定义数据属性,django,django-crispy-forms,Django,Django Crispy Forms,我想覆盖复选框SelectMultiple,以便使用以下逻辑为表单提供数据属性: 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

我想覆盖复选框SelectMultiple,以便使用以下逻辑为表单提供数据属性:

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表单很有效,但crispy从不调用此方法,因此不会以这种方式工作。我想覆盖复选框SelectMultiple create_选项方法。 解决此问题而不必覆盖整个表单字段渲染过程的优雅方法是什么? 我尝试使用自定义html,但要获得一个具有checked属性的正常工作的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

您是否尝试从
django.forms.CheckboxSelectMultiple
继承一个类?是的,这就是我希望与您分享的从这个类继承的代码。