Login

Multiple Select Widget with jQueryUI

Author:
maguspk
Posted:
June 23, 2010
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

This widget can be imported in your forms.py file and used like so:

formfield = forms.ModelMultipleChoiceField(widget=MultiSelectWidget, queryset=Model.objects.all())

The javascript is provided by Michael's Multiselect. In addition to the javascript you will need jQuery (the latest release is fine) and jQuery UI. The convenient thing is that this widget will style to match whichever jQuery UI you've 'rolled' or selected, making it highly customizable!

Hopefully this helps others who wanted a nice widget with jQuery and were sad to find there were no nice default options, enjoy! :)

 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
class MultiSelectWidget(forms.SelectMultiple):
    class Media:
        css = {
            'all': (
                iasettings.MEDIA_URL + 'js/michael-multiselect/css/ui.multiselect.css',
            )
        }
        js = (
            iasettings.MEDIA_URL + 'js/michael-multiselect/js/plugins/tmpl/jquery.tmpl.1.1.1.js',
            iasettings.MEDIA_URL + 'js/michael-multiselect/js/plugins/blockUI/jquery.blockUI.js',
            iasettings.MEDIA_URL + 'js/michael-multiselect/js/ui.multiselect.js',
        )

    def __init__(self, language=None, attrs=None):
        self.language = language or settings.LANGUAGE_CODE[:2]
        super(MultiSelectWidget, self).__init__(attrs=attrs)

    def render(self, name, value, attrs=None):
        rendered = super(MultiSelectWidget, self).render(name, value, attrs)
        return rendered + mark_safe(u'''<script type="text/javascript">
            $(document).ready(function afterReady() {
                var elem = $('#id_%(name)s');
                elem.multiselect();
            });
            </script>''' % {'name':name})

More like this

  1. LazyPrimaryKeyRelatedField by LLyaudet 6 days, 4 hours ago
  2. CacheInDictManager by LLyaudet 6 days, 10 hours ago
  3. MYSQL Full Text Expression by Bidaya0 1 week ago
  4. Custom model manager chaining (Python 3 re-write) by Spotted1270 1 week, 6 days ago
  5. Django Standard API Response Middleware for DRF for modern frontend easy usage by Denactive 4 weeks, 1 day ago

Comments

Please login first before commenting.