循环复选框并非所有值都添加到数据库

时间:2013-03-21 09:48:04

标签: django

我有以下功能,它应该做什么循环在一个名为groups的复选框中提交的值,然后将每个值提交给数据库。但是,它似乎只向数据库添加一个值。有什么不对吗?

groups = 1,3,3,4

功能更新

def add_batch(request):
    # If we had a POST then get the request post values.
    if request.method == 'POST':
        form = BatchForm(request.POST)
        # Check we have valid data before saving trying to save.
        if form.is_valid():
            # Clean all data and add to var data.
            data = form.cleaned_data
            groups = data['groups'].split(",")
            for item in groups:
                batch = Batch(content=data['message'],
                              group=Group.objects.get(pk=item),
                              user=request.user
                              )
                batch.save()
    return redirect(batch.get_send_conformation_page())

发布消息:

groups  1, 3, 4

形式:

<form action="{% url 'add_batch' %}" method="post" class="form-horizontal" enctype="multipart/form-data" >
     {% for item in groups %}
         <label class="groups">
            <input type="checkbox" name="groups" value="{{ item.id }}" /> {{item.name}}<br />
         </label>

     {% endfor %}
</form>

forms.py

class BatchForm(forms.Form):

    groups = forms.CharField(max_length=100)

1 个答案:

答案 0 :(得分:2)

看起来您在页面上有多个复选框,每个复选框的名称都为groups。这完全没问题。

当你提交这样的表格时,参数可能如下所示:

?groups=1&groups=3&groups=4

另一方面,您的表单定义将组定义为CharField。它将使用从request.GET['groups']检索到的值填充,该值仅检索上述值之一。

如果您将groups定义为:

,我认为您会更好
CHOICES = (
(0, '1'),
(1, '2'),
(2, '3'),
)

class MyForm(forms.Form):
    groups = forms.MultipleChoiceField(
            choices=CHOICES, 
            label="Groups", 
            required=False)