2013-03-21 19 views
0

我有以下功能,它應該做什麼循環在一個名爲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()) 

POST變量:

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) 
+2

請不要用'的項目範圍(LEN(組))'。 '對於組中的項目'更清晰,那麼'item'就是你需要的實際對象。 – 2013-03-21 10:18:31

+0

你可以發佈你的Django表單嗎? – Vincent 2013-03-21 10:20:26

+0

@Daniel for groups給我的列表索引必須是整數,而不是unicode – Prometheus 2013-03-21 10:48:07

回答

1

它看起來像你有一個頁面上的多個複選框,每個人都有名字groups。這非常好。

當您提交這樣的形式下,PARAMS可能看起來像這樣:

?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) 
+0

可以選擇在這種情況下來自一個查詢? – Prometheus 2013-03-21 11:45:20

+1

@Spike使用forms.ModelMultipleChoiceField,它接受一個查詢集。 – 2013-03-21 11:58:21

+0

謝謝你真的幫了忙。 – Prometheus 2013-03-21 12:09:03

相關問題