Django MultipleChoiceField用户选择会引发错误

时间:2015-02-05 22:15:43

标签: python django django-forms

我正在尝试编写一个表单,允许用户根据需要从特定组中选择尽可能多的用户。但是,当我尝试使用用户列表作为选项时,我收到一条错误消息,指出“用户”对象不支持索引。

它是一种相当标准的形式,主要区别在于该组是根据传递给表单的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 个答案:

答案 0 :(得分: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)]

这将返回一个符合

组合的列表
[('user1.pk', 'user1.email'), ('user2.pk', 'user2.email'),...]

可用作choices