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))
解決了它,謝謝! – 2015-02-06 16:04:08