- Author:
- notanumber
- Posted:
- May 4, 2012
- Language:
- Python
- Version:
- Not specified
- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.