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..
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With