Login

Support disabling options in a select widget

Author:
jackton1
Posted:
April 30, 2018
Language:
Python
Version:
Not specified
Score:
2 (after 2 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

  1. "Magic Link" Management Command by webology 3 months ago
  2. Closest ORM models to a latitude/longitude point by simonw 3 months ago
  3. Log the time taken to execute each DB query by kennyx46 3 months ago
  4. django database snippet by ItsRLuo 3 months ago
  5. Serialize a model instance by chriswedgwood 4 months ago

Comments

Please login first before commenting.