Python Question

How to get current signed user in forms.py?

I'm using ModelChoiceField to select Invoice provider in my forms. In the current case, I'm returning all the Providers to the queryset.

But I should return only Providers that created by the signed user. Provider has a ForeignKey field named

user
.

Here is my Form:

class InvoiceCreationForm(forms.Form):
# ...
provider = forms.ModelChoiceField(
label='Provider',
required=False,
queryset=Provider.objects.all(),
widget=forms.Select(attrs={
'name': 'provider',
'class': 'form-control',
'id': 'input-invoice-provider',
})
)


I need to filter objects like this:

Provider.objects.filter(user=current_user)


How can I get the signed user? Or how can I get the
request
object outside of a view? I tried get the current user from
__init__
method of the form then set it to
self.user
. But I can't use it in the query like
self.user
.

Answer

Getting the user in __init__() is only the first part of the solution. You also need to use that user to filter the queryset:

class InvoiceCreationForm(forms.Form):
    def __init__(self, *args, **kwargs):
         self.user = kwargs.pop('user', None)
         super(InvoiceCreationForm, self).__init__(*args, **kwargs)
         if self.user:
             self.fields['provider'].queryset = Provider.objects.filter(user=self.user)
Comments