A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Django: Creating multiple select checkboxes with Forms

I got stuck for almost an hour trying to create a multiple select checkbox. Here is how to do it:

First, I put this in my forms.py

class UserlistForm(forms.Form):
    users = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,label="Notify and subscribe users to this post:")

Then in my views.py I have something like this:

def post_message(request, groupid):
    custgroup = Group.objects.get(id=groupid)
    groupusers = User.objects.filter(groups__name=custgroup.name)
    userlistform = UserlistForm()
    #This fills up the "choices"
    userlistform.fields['users'].choices = 
        [(x.id, x) for x in User.objects.filter(groups__name=custgroup.name)]
    data = {"userlistform":userlistform,}
    return render_to_response("message/view_message.html",
                          data, context_instance=RequestContext(request))

In your template, you should just display userlistform:


I forgot to mention that when you want to get the “list” of selected items you use this:

userlist = request.POST.getlist('users')
you will get something like this:
[u'1', u'2', u'3']
This entry was posted in General and tagged , , , , . Bookmark the permalink.

3 Responses to Django: Creating multiple select checkboxes with Forms

  1. jack says:

    this saved me! thanks

  2. Thanga Vignesh Raja says:

    code working fine..!!!! thanks a lot:)

  3. Derek says:

    Hi; please check when you post code that the line length is 80 chars or less. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>