Login

DisableableSelectWidget

Author:
notanumber
Posted:
May 4, 2012
Language:
Python
Version:
Not specified
Tags:
form select widget
Score:
0 (after 0 ratings)

A Select widget that allows choices to be disabled. Specify disabled_choices to indicate which choices should be present in the list, but disabled.

A possible use case for this is a form that displays data that can be edited by privileged user's but only viewed by others.

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

class DisableableSelectWidget(forms.Select):
    def __init__(self, attrs=None, disabled_choices=(), choices=()):
        super(DisableableSelectWidget, self).__init__(attrs, choices)
        self.disabled_choices = list(disabled_choices)

    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"'
            if not self.allow_multiple_selected:
                # Only allow for a single selection.
                selected_choices.remove(option_value)
        else:
            selected_html = ''
        if option_value in self.disabled_choices:
            disabled_html = u' disabled="disabled"'
        else:
            disabled_html = ''
        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. Allow disabling options in a select widget by scjody 3 years, 10 months ago
  2. DropDownMultiple widget by marinho 6 years, 11 months ago
  3. TableSelectMultiple Widget by insin 7 years, 4 months ago
  4. labeled hidden input with choices by eliasfernandez 2 years, 5 months ago
  5. Readonly Select Widget Replacement by colinkingswood 4 months, 2 weeks ago

Comments

Please login first before commenting.