CheckboxSelectMultiple in crispy forms, custom data attribute

Viewed 271

I want to override the CheckboxSelectMultiple so I can give data- attributes to the form using the logic below:

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

This works just fine for non-crispy forms but since crispy never call this method, it won'w work this way. I want to override the CheckboxSelectMultiple create_option method. What is an elegant way to solve this issue without having to override the whole form field rendering process? I tried to use a custom html but it is so complicated (for my skills) to get a decent working CheckboxSelectMultiple with the checked attribute.

This is what I did so far:

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 Answers
Related