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

1👍

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)
👤Nick

Leave a comment