[Fixed]-Django pass User instance to Forms when form is created


If you do this code in field declaration section like

class QuestionForm(forms.Form):
    ref = forms.ModelChoiceField(queryset=Study.objects.filter(owner=...)

then it will not work because it still doesn’t have self variable.

You can do this in init method like this

class QuestionForm(forms.Form):
    ref = forms.ModelChoiceField()
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['ref'].queryset = Study.objects.filter(owner=request.user)

Leave a comment