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:
{{userlistform.as_p}} |
EDIT:
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 saved me! thanks
code working fine..!!!! thanks a lot:)
Hi; please check when you post code that the line length is 80 chars or less. Thanks!