1

I am working on a custom requirement which demands to customise select option attributes. My dropdown will show the list of options, and some of those options should be shown as disabled as per certain conditions.

List of options along with disabled options

I have tried customising the Select widget attributes by passing disabled = disabled. But that disables the whole dropdown. By looking into the code of django 1.11.5, it seems that the attributes applied on Select will be applied to its options.

Can anyone please suggest how this functionality can be achieved?

Thank you

Amarjeet Kaur
  • 157
  • 4
  • 14
  • There is a general solution which works for Django 2.+ and allows to add a title and other things in options, see https://stackoverflow.com/a/56097149/1788851 – Edouard Thiel May 12 '19 at 12:03

1 Answers1

3

I think you can sub-class the django.forms.widgets.Select widget, passing new parameter disabled_choices to its __init__ function and override the create_option method like this:

class MySelect(Select):

    def __init__(self, attrs=None, choices=(), disabled_choices=()):
        super(Select, self).__init__(attrs, choices=choices)
        # disabled_choices is a list of disabled values
        self.disabled_choices = disabled_choices

    def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
        option = super(Select, self).create_option(name, value, label, selected, index, subindex, attrs)
        if value in self.disabled_choices:
           option['attrs']['disabled'] = True
        return option

Hope this helps.

Mihayl
  • 3,821
  • 2
  • 13
  • 32
Phuong Nguyen
  • 306
  • 2
  • 1
  • Thank you so much. It is really a great help. I could get it working after doing some minor alterations :-) – Amarjeet Kaur Sep 15 '17 at 06:37
  • I have defined a complete example of this using a ModelForm here: https://stackoverflow.com/questions/673199/disabled-option-for-choicefield-django/55348111#55348111 – Rob Mar 26 '19 at 01:15