Login

Support disabling options in a select widget

Author:
jackton1
Posted:
April 30, 2018
Language:
Python
Version:
Not specified
Tags:
widgets django-forms
Score:
1 (after 1 ratings)

Provide the ability to disable a select option with Django2. This can be done during the widget initialization (i.e when the widget field is created) or during form initialization.

This will disable the select option based on a context or by specifying the values that should be disabled.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# You can either pass a list of values to be disabled i.e

#    def __init__(self, disabled_choices, *args, **kwargs):
#            self._disabled_choices = disabled_choices
#  OR
from django.forms import Select


class SelectWidget(Select):
    """
    Subclass of Django's select widget that allows disabling options.
    """

    def __init__(self, *args, **kwargs):
        self._disabled_choices = []
        super().__init__(*args, **kwargs)

    @property
    def disabled_choices(self):
        return self._disabled_choices

    @disabled_choices.setter
    def disabled_choices(self, other):
        self._disabled_choices = other

    def create_option(self, name, value, *args, **kwargs):
        option_dict = super().create_option(name, value, *args, **kwargs)
        if value in self.disabled_choices:
            option_dict['attrs']['disabled'] = 'disabled'
        return option_dict

# To disabled an option based on a condition i.e user isn't a superuser.

class MyForm(forms.Form):
    status = forms.ChoiceField(required=True, widget=SelectWidget, choices=Status.choices())
    
    def __init__(self, request, *args, **kwargs):
        if not request.user.is_superuser:
            self.fields['status'].widget.disabled_choices = [1, 4]
        super().__init__(*args, **kwargs)

More like this

Comments

Please login first before commenting.