Allow disabling options in a select widget

 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
from django.forms.widgets import Select
from django.utils.encoding import force_unicode
from django.utils.html import escape, conditional_escape


class SelectWithDisabled(Select):
    """
    Subclass of Django's select widget that allows disabling options.
    To disable an option, pass a dict instead of a string for its label,
    of the form: {'label': 'option label', 'disabled': True}
    """
    def render_option(self, selected_choices, option_value, option_label):
        option_value = force_unicode(option_value)
        if (option_value in selected_choices):
            selected_html = u' selected="selected"'
        else:
            selected_html = ''
        disabled_html = ''
        if isinstance(option_label, dict):
            if dict.get(option_label, 'disabled'):
                disabled_html = u' disabled="disabled"'
            option_label = option_label['label']
        return u'<option value="%s"%s%s>%s</option>' % (
            escape(option_value), selected_html, disabled_html,
            conditional_escape(force_unicode(option_label)))

More like this

  1. CheckboxMultiSelect with interable checkboxes by pyramids16 1 year, 5 months ago
  2. DisableableSelectWidget by notanumber 1 year, 11 months ago
  3. Dynamically change a form select widget to a hidden widget by epicserve 4 years, 9 months ago
  4. Allow disabling options in a checkboxselectmultiple widget by sterkh 1 year, 9 months ago
  5. FieldAccessForm (per-field user access for forms derived from models) by Killarny 5 years, 6 months ago

Comments

(Forgotten your password?)