Skip to content Skip to sidebar Skip to footer

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:

  1. 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.
  2. The __init__ function checks which choices exist already in symbols and updates the UPDATED_CHOICES accordingly.
  3. A field named symbol gets added to the form from the constructor, which have as choices the UPDATED_CHOICES.

Post a Comment for "How To Disable Checkboxes In Multiplechoicefield?"