Simplify the DisableableSelectionWidget
Signed-off-by: Roberto Rosario <roberto.rosario.gonzalez@gmail.com>
This commit is contained in:
@@ -1,38 +1,23 @@
|
|||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django import forms
|
from django import forms
|
||||||
from django.utils.encoding import force_text
|
|
||||||
from django.utils.html import format_html
|
|
||||||
from django.utils.safestring import mark_safe
|
from django.utils.safestring import mark_safe
|
||||||
|
|
||||||
|
|
||||||
class DisableableSelectWidget(forms.SelectMultiple):
|
class DisableableSelectWidget(forms.widgets.SelectMultiple):
|
||||||
allow_multiple_selected = True
|
def create_option(self, *args, **kwargs):
|
||||||
|
result = super(DisableableSelectWidget, self).create_option(*args, **kwargs)
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
# Get a keyword argument named value or the second positional argument
|
||||||
self.disabled_choices = kwargs.pop('disabled_choices', ())
|
# Current interface as of Django 1.11
|
||||||
super(DisableableSelectWidget, self).__init__(*args, **kwargs)
|
# def create_option(self, name, value, label, selected, index,
|
||||||
|
# subindex=None, attrs=None):
|
||||||
|
value = kwargs.get('value', args[1])
|
||||||
|
|
||||||
def render_option(self, selected_choices, option_value, option_label):
|
if value in self.disabled_choices:
|
||||||
if option_value is None:
|
result['attrs'].update({'disabled': 'disabled'})
|
||||||
option_value = ''
|
|
||||||
option_value = force_text(option_value)
|
return result
|
||||||
if option_value in selected_choices:
|
|
||||||
selected_html = mark_safe(' 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 format_html('<option value="{0}"{1}{2}>{3}</option>',
|
|
||||||
option_value,
|
|
||||||
selected_html,
|
|
||||||
disabled_html,
|
|
||||||
force_text(option_label))
|
|
||||||
|
|
||||||
|
|
||||||
# From: http://www.peterbe.com/plog/emailinput-html5-django
|
# From: http://www.peterbe.com/plog/emailinput-html5-django
|
||||||
|
|||||||
Reference in New Issue
Block a user