"Disabled" option for choiceField - Django

Django's form widgets offer a way to pass a list of attributes that should be rendered on the <option> tag:

my_choices = ( ('one', 'One'), ('two', 'Two'))
class MyForm(forms.Form):
    some_field = forms.ChoiceField(choices=my_choices, 
                                   widget=forms.Select(attrs={'disabled':'disabled'}))

Unfortunately, this won't work for you because the attribute will be applied to EVERY option tag that is rendered. Django has no way to automatically know which should be enabled and which should be disabled.

In your case, I recommend writing a custom widget. It's pretty easy to do, and you don't have that much custom logic to apply. The docs on this are here. In short though:

  • subclass forms.Select, which is the default select renderer
  • in your subclass, implement the render(self, name, value, attrs) method. Use your custom logic to determine if the value qualifies as needing to be disabled. Have a look at the very short implementation of render in django/forms/widgets.py if you need inspriation.

Then, define your form field to use your custom widget:

class MyForm(forms.Form):
    some_field = forms.ChoiceField(choices=my_choices, 
                                   widget=MyWidget)

You can create Choices as mentioned by Bryan like this. In the below options Root 1, Root 2 are automatically disabled and they will look like Group Options

CHOICES = (
  ('-- Root 1--', 
      (
        ('ELT1', 'ELT1'),
        ('ELT2', 'ELT2'),
        ('ELT3', 'ELT3'),
      )
   ),
  ('-- Root 2--', 
      (
        ('ELT3', 'ELT3'),
        ('ELT4', 'ELT4'),
      )
  ),
)

The above option will display like this. In the below image, Root 1 and Root 2 are not selectable.

enter image description here

Hope this will clear your problem

-Vikram

Tags:

Django