Skip to content Skip to sidebar Skip to footer

Disable Choice In Modelmultiplechoicefield Checkboxselectmultiple Django

All, I have researched this for a couple of days, and can't quite seem to find what I'm looking for. I am well aware of using the following to disable a field in a Django form: se

Solution 1:

I created my custom widget with one method overridden:

MY_OPTION = 0
DISABLED_OPTION = 1
ITEM_CHOICES = [(MY_OPTION, 'My Option'), (DISABLED_OPTION, 'Disabled Option')]

classCheckboxSelectMultipleWithDisabledOption(forms.CheckboxSelectMultiple):defcreate_option(self, *args, **kwargs):
        options_dict = super().create_option(*args, **kwargs)

        if options_dict['value'] == DISABLED_OPTION:
            options_dict['attrs']['disabled'] = ''return options_dict

And then in the form:

classMyForm(forms.Form):

    items = forms.MultipleChoiceField()

    def__init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['items'].widget = CheckboxSelectMultipleWithDisabledOption()
        self.fields['items'].choices = ITEM_CHOICES

For more complicated cases you can override your custom widget's __init__ and pass additional arguments there (in my case I had to pass my form's initial value).

Post a Comment for "Disable Choice In Modelmultiplechoicefield Checkboxselectmultiple Django"