如何从Django中的复选框中获取多个值

Naz*_*han 44 python django checkbox django-models

我想使用request.POST['xzy']列表获取多选复选框的值.这是我的模型和模板代码.

我的模特

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

我的模板

{% 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 %}
Run Code Online (Sandbox Code Playgroud)

我的查看代码

if request.method == 'POST': 
  recommendations=request.POST['recommendations']
Run Code Online (Sandbox Code Playgroud)

在这里,我希望"推荐"成为包含所有朋友ID的列表,但是这里只是被覆盖并且仅包含在最后一次for循环迭代中分配的值.我怎么解决这个问题.绝望地需要帮助.谢谢.

Ign*_*ams 107

request.POST.getlist('recommendations')
Run Code Online (Sandbox Code Playgroud)