diff options
Diffstat (limited to 'ishtar_common/widgets.py')
| -rw-r--r-- | ishtar_common/widgets.py | 45 | 
1 files changed, 40 insertions, 5 deletions
diff --git a/ishtar_common/widgets.py b/ishtar_common/widgets.py index b80faee6d..efea07065 100644 --- a/ishtar_common/widgets.py +++ b/ishtar_common/widgets.py @@ -126,16 +126,23 @@ class Select2Media(object):          return media -class Select2Dynamic(Select2Media, forms.Select): +class Select2DynamicBase(Select2Media):      """      Select input using select, allowing dynamic creation.      """ +    MULTIPLE = False      def render(self, name, value, attrs=None, choices=()):          choices = choices or getattr(self, "choices", []) -        if value and value not in [key for key, v in choices]: -            choices.insert(1, (value, value)) -            self.choices = choices +        if value: +            values = [value] +            if self.MULTIPLE: +                value = value[0] +                values = value +            for va in values: +                if va not in [key for key, va in choices]: +                    choices.insert(1, (va, va)) +                    self.choices = choices          klass = attrs and attrs.get("class") or ""          klass += " " if klass else "" + "js-select2"          if not attrs: @@ -161,7 +168,9 @@ class Select2Dynamic(Select2Media, forms.Select):          if attrs.get("full-width", None):              options.append("containerCssClass: 'full-width'") -        html = super(Select2Dynamic, self).render(name, value, attrs) +        if self.MULTIPLE: +            options.append("multiple: 'true'") +        html = super(Select2DynamicBase, self).render(name, value, attrs)          html += """<script type="text/javascript">          $(document).ready(function() {{              $("#id_{}").select2({{ {} }}); @@ -172,6 +181,14 @@ class Select2Dynamic(Select2Media, forms.Select):          return mark_safe(html) +class Select2Dynamic(Select2DynamicBase, forms.Select): +    MULTIPLE = False + + +class Select2DynamicMultiple(Select2DynamicBase, forms.SelectMultiple): +    MULTIPLE = True + +  class Select2DynamicField(forms.ChoiceField):      widget = Select2Dynamic @@ -190,6 +207,24 @@ class Select2DynamicField(forms.ChoiceField):          return super(Select2DynamicField, self).to_python(value).strip() +class Select2DynamicMultipleField(forms.MultipleChoiceField): +    widget = Select2DynamicMultiple + +    def validate(self, value): +        """ +        Key can be added dynamically. Only check that the character " is not +        used. +        """ +        if value and '"' in value: +            raise ValidationError(_('The character " is not accepted.')) + +    def to_python(self, value): +        """ +        Strip value +        """ +        return [v.strip() for v in super().to_python(value)] + +  class Select2Base(Select2Media):      def __init__(          self, attrs=None, choices=(), remote=None, model=None, new=None, available=None  | 
