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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4359238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:25:11  来源:igfitidea点击:

How do I get multiple values from checkboxes in Django

pythondjangodjango-modelscheckbox

提问by NazimZeeshan

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.

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

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.

在这里,我希望“推荐”是一个包含所有朋友 ID 的列表,但在这里它只是被覆盖,并且只包含在最后一次 for 循环迭代中分配的值。我怎么解决这个问题。迫切需要帮助。谢谢你。

采纳答案by Ignacio Vazquez-Abrams

request.POST.getlist('recommendations')

回答by Dan

if not request.POST.has_key(strName):
      return ""    
  if request.POST[strName]:
      return ','.join(request.POST.getlist(strName))          
  else:
      return ""