How To Disable Checkboxes In Multiplechoicefield?
I use MultipleChoiceField in form. It shows me REQUIREMENTS_CHOICES list with checkboxes where user can select and add new requirements to database. Is it possible to disable check
Solution 1:
You can manipulate your form at it's initialization:
REQUIREMENTS_CHOICES = (
('A', 'Name A'),
('B', 'Name B'),
('C', 'Name C'),
('D', 'Name D'),
)
classRequirementAddForm(forms.ModelForm):
def__init__(self, symbols='', *args, **kwargs):
super(RequirementAddForm, self).__init__(*args, **kwargs)
UPDATED_CHOICES = () # empty tuplefor choice in REQUIREMENTS_CHOICES:
if choice[1] notin symbols:
UPDATED_CHOICES += (choice,) # adds choice as a tuple
self.fields['symbol'] = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple,
choices=UPDATED_CHOICES,
)
classMeta:
model = Requirement
What happens above:
- When you initialize your form
(ex:
form=RequirementAddForm(symbols=existing_symbols)
), you can pass to the constructor, a string with the existing symbols for an item in your database. - The
__init__
function checks which choices exist already insymbols
and updates theUPDATED_CHOICES
accordingly. - A field named
symbol
gets added to the form from the constructor, which have as choices theUPDATED_CHOICES
.
Post a Comment for "How To Disable Checkboxes In Multiplechoicefield?"