我在forms.py
这段代码中写道
id_group = forms.ModelChoiceField(queryset=StudentsGroup.objects.filter(id_teacher=1))
如何将1
更改为当前登录的用户?
我尝试执行此操作User.objects.get(username=request.user.get_username())
但不起作用
答案 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