Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get multiple values from checkboxes in Django

I want to get values of a multiple select check box using request.POST['xzy'] as a list. Here is my model and template code.

My Model

class Recommend(models.Model):   user=models.ForeignKey(User)   book=models.ForeignKey(BookModel)   friends=models.ManyToManyField(User, related_name="recommended") 

My Template

{% for friend in friends %}  <input type="checkbox" name="recommendations" id="option{{friend.id}}" value={{friend.username}} /> <label for="option{{friend.id}}"><b>{{friend.username}}</b></label><br />  {% endfor %} 

My View code

if request.method == 'POST':    recommendations=request.POST['recommendations'] 

Here I want 'recommendations' to be a list containing all friend ids but here it is just getting overwritten and only contains the value that got assigned in the last for loop iteration. How can I solve this problem. Need help desperately. Thank You.

like image 546
NazimZeeshan Avatar asked Dec 05 '10 14:12

NazimZeeshan


People also ask

Can checkbox select multiple values?

A checkbox is a tiny user interface component that allows users to select more than one option from a given options list. We will create a small fruits list using HTML 5 and display that checkboxes list to the users to select more than one option.


2 Answers

request.POST.getlist('recommendations') 
like image 60
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 14:10

Ignacio Vazquez-Abrams


if not request.POST.has_key(strName):       return ""       if request.POST[strName]:       return ','.join(request.POST.getlist(strName))             else:       return "" 
like image 20
Dan Avatar answered Oct 02 '22 13:10

Dan