Disable Choice In ModelMultipleChoiceField CheckBoxSelectMultiple Django

后端 未结 1 739
春和景丽
春和景丽 2021-01-19 05:12

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

1条回答
  •  天涯浪人
    2021-01-19 05:21

    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')]
    
    class CheckboxSelectMultipleWithDisabledOption(forms.CheckboxSelectMultiple):
    
        def create_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:

    class MyForm(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).

    0 讨论(0)
提交回复
热议问题