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'' % ( escape(option_value), selected_html, disabled_html, conditional_escape(force_unicode(option_label)))