Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - can I get the current user when I'm not in a view function

I have Company and CompanyUser models. CompanyUser has 1:1 relationship with the django's auth User model. Every user is part of some company, so I have a ForeignKey field (Company) in the CompanyUser model:

class CompanyUser(models.Model):
    Company = models.ForeignKey(Company)
    User = models.OneToOneField(User)

Now I want to create some html tables to view and filter the data about Sales, Products, etc. I'm using django-tables2 and that works great.

Now let's say I want to see the Sales of a particular Product. So I need a dropdown that contains all Products of the Company that the user belongs to.

I've have created the forms.py file in my app:

from django import forms

class SaleFilterForm(forms.Form):
    product_id = forms.ChoiceField(queryset=Product.objects.all(Company=???))
    ...
    ...

So my question is. How to get the current user, when I'm inside forms.py file? I don't have the "request" object there..

like image 649
user568021 Avatar asked Dec 04 '25 04:12

user568021


1 Answers

Views.py

def yourview(request):
    yourform = SaleFilterForm(request.POST, user=request.user)

Forms.py

class SaleFilterForm(forms.Form):
    ...

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(SaleFilterForm, self).__init__(*args, **kwargs)

Then you can use your user inside of your form as self.user

Hope it helps!

like image 115
Lara Avatar answered Dec 06 '25 17:12

Lara