Django TypeError' User'对象不可迭代

时间:2015-05-15 12:59:50

标签: python django

是否无法使用User.objects.all()迭代User对象? 我试图做同样但无济于事

我有一张表格;

class AddMemberForm(Form):
    user = forms.ChoiceField(choices=User.objects.all(),
                             initial='Choose a User',
    ) 

我正在尝试通过模板呈现它。 views.py的相应部分如下;

class StationHome(View):
    def get(self, request, pk):
        station = Station.objects.get(pk=pk)
        channels = Channel.objects.filter(station=station)
        members = station.members.all()
        form1 = AddMemberForm()
        return render(request, 
                      "home_station.html",
                      {"form1":form1,
                       "station":station,
                       "channels":channels,
                       "members":members,
                   },
                  )

最后相应模板的相应部分,

<form method="post" action="{% url 'add_member' station.pk %}">
    {% csrf_token %}
    {{ form1 }}
</form>

但由于此表单,我无法访问该网址。我收到了TypeError at相应的网址'User' object is not iterable错误。

有人请帮忙。

1 个答案:

答案 0 :(得分:3)

使用ModelChoiceField代替简单ChoiceField

user = forms.ModelChoiceField(queryset=User.objects.all(),
                              empty_label="(Choose a User)")

更新:您可以在表单的构造函数中更改查询集。例如,如果要从表单中排除已添加的成员:

class AddMemberForm(Form):
    ...
    def __init__(self, *args, **kwargs):
        station = kwargs.pop('station')
        super(AddMemberForm, self).__init__(*args, **kwargs)
        if station:
            self.fields['user'].queryset = User.objects.exclude(
                                             id__in=station.members.all())

然后使用station参数创建表单:

form1 = AddMemberForm(station=station)