Django ModelChoseField仅限于当前登录的用户

时间:2015-12-10 10:58:27

标签: django

我在forms.py这段代码中写道

id_group = forms.ModelChoiceField(queryset=StudentsGroup.objects.filter(id_teacher=1))

如何将1更改为当前登录的用户?

我尝试执行此操作User.objects.get(username=request.user.get_username())但不起作用

1 个答案:

答案 0 :(得分:1)

在视图中初始化时,您需要将当前用户传递给from:form = MyForm(user=request.user),然后您可以在表单中执行以下操作:

class MyForm(ModelForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(MyForm, self).__init__(*args, **kwargs)
        groups = StudentsGroup.objects.filter(id_teacher=self.user.pk)
        self.fields['id_group'].queryset = groups