问题
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:
self.fields['author'].disabled = True
The above will disable a field entirely. I am trying to display a checkbox with multiple select options, but I want one of the choices to be automatically selected and disabled so the user can not change it as one of the choices they have selected. Here is the code that I've been using to display the checkbox and it works fine:
self.fields['author'] = forms.ModelMultipleChoiceField(
queryset=User.objects.all(),
widget=forms.CheckboxSelectMultiple(),
initial = user.favorite)
The user.favorite is displaying as I would expect, but I'd like to disable it so that it's still checked, but the user can't change it, but they can still select others in the checkbox. Is this possible? Thanks in advance.
回答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')]
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).
来源:https://stackoverflow.com/questions/48935945/disable-choice-in-modelmultiplechoicefield-checkboxselectmultiple-django