2015-02-05 59 views
0

我想寫一個表單,允許用戶從特定的組中選擇儘可能多的用戶。但是,當我嘗試使用用戶列表作爲選項時,我收到一個錯誤消息,說'用戶'對象不支持索引。Django MultipleChoiceField用戶選擇引發錯誤

它是一個相當標準的形式,主要區別在於該組是基於傳遞給表單的kwarg過濾的。該表單傳遞一個project_id(項目對象主鍵),然後找到與該項目關聯的組並生成該字段。

從forms.py

class ModifyTeamForm(forms.Form): 

    action = ChoiceField(choices=[('remove', 'Remove users'), ('promote', 'Promote to lead.')]) 



    def __init__(self, *args, **kwargs): 

     # The project to get the team for 
     project_id = kwargs.pop('project_id', None) 

     super(ModifyTeamForm, self).__init__(*args, **kwargs) 

     project = Project.objects.get(pk=project_id) 

     # Team for this project 
     team = User.objects.filter(groups__name=project.project_name) 

     # Create a form field to select current team members 
     current_team = MultipleChoiceField(required=True, choices = team, widget=CheckboxSelectMultiple) 

     # Add the field 
     self.fields['current_team'] = current_team 

我views.py

@login_required 
def team(request, project_id): 

    if request.method == "POST": 
     # Not yet implemented 
     return 
    else: 
     form = ModifyTeamForm(project_id=project_id) 

     template = loader.get_template('projects/team.html') 

     context = RequestContext(request, { 
      'form': form, 
     }) 

     return HttpResponse(template.render(context)) 

回答

1

這是因爲MultipleChoiceField.choices有望成爲一個二維數組有效(https://docs.djangoproject.com/en/1.7/ref/forms/fields/#django.forms.ChoiceField.choices)。

所以你可以做這樣的事情:

team = [(u.pk, u.email) for u in User.objects.filter(groups__name=project.project_name)] 

這將返回一個列表continaing的

[('user1.pk', 'user1.email'), ('user2.pk', 'user2.email'),...] 

的combintation這將是可用的choices

+0

解決了它,謝謝! – 2015-02-06 16:04:08

相關問題