如何从Django中的复选框获取多个值 [英] How do I get multiple values from checkboxes in Django

查看:127
本文介绍了如何从Django中的复选框获取多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我的模型

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

我的模板 p>

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 %}

strong>

My View code

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

这里我想建议是一个包含所有朋友id的列表,但这里它正在覆盖并且只包含在最后一次循环迭代中分配的值。我如何解决这个问题。需要帮助拼命。谢谢。

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.

推荐答案

request.POST.getlist('recommendations')

这篇关于如何从Django中的复选框获取多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆