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. Template tag - list punctuation for a list of items by shapiromatron 6 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 6 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 1 month ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 1 month ago
  5. Help text hyperlinks by sa2812 1 year, 2 months ago

Comments

Please login first before commenting.