2013-03-22 66 views
0

我希望你能看到我想在這裏做什麼,只是我想迭代組看起來像group = 1,3,5等的值並將它們添加到數據庫中。組是一個複選框。所以我想使用拆分選項。我收到以下消息壽....Django'QuerySet'對象沒有屬性'拆分'

「查詢集」對象有沒有屬性「分裂」

所以這是我的理解它是在我使用的填充這是一種查詢形式的init,我需要這個,但在發佈後,它應該只是一個列表。我做錯了什麼?

view.py

form = BatchForm(request.user, 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['group'].split(",") 
      for item in form.cleaned_data['group']: 
       batch = Batch(content=data['content'], 
           group=Group.objects.get(pk=item), 
           user=request.user 
          ) 
       batch.save() 

forms.py

class BatchForm(forms.ModelForm): 


    class Meta: 
     model = Batch 
     exclude = ('user', 'group') 



    def __init__(self, user=None, *args, **kwargs): 
     super(BatchForm, self).__init__(*args,**kwargs) 
     if user is not None: 
      form_choices = Group.objects.for_user(user) 
     else: 
      form_choices = Group.objects.all() 
     self.fields['group'] = forms.ModelMultipleChoiceField(
      queryset=form_choices 
     ) 

template.py

{% for value, text in form.group.field.choices %} 


    <input type="checkbox" name="group" value="{{ value }}" /> {{text}}<br /> 

{% endfor %} 

回答

5

因爲你使用的是清潔的數據,這是一個ModelMultipleChoice場,它實際上是一個queryset

嘗試這樣:

form = BatchForm(request.user, 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 
     for group in data['group']: 
      batch = Batch(
       content=data['content'], 
       group=group, 
       user=request.user 
      ) 
      batch.save() 
1
if form.is_valid(): 
     # Clean all data and add to var data. 
     data = form.cleaned_data 
     groups = [x.group for x in form.cleaned_data['group']] 
     for item in groups: 
      batch = Batch(content=data['content'], 
          group=Group.objects.get(pk=item), 
          user=request.user 
         ) 
      batch.save()