Ad
How To Get Current User In Forms?
I have a form in my Django project. In this form I can assign person. This is my form:
class AssignForm(forms.ModelForm):
user = forms.ModelChoiceField(
queryset=UserProfile.objects.filter(is_active=True)
label=_(u'User')
)
class Meta:
model = Customer
fields = ('user',)
I want to add another filter in this form. It is company
. I get a list of all users in this form but I want to just listing the users that belongs to current user's company.
So it should be :
queryset=UserProfile.objects.filter(is_active=True, company = current_user.company)
But I cannot get requests from forms. How can I handle it?
Ad
Answer
You override the constructor of the form with:
class AssignForm(forms.ModelForm):
user = forms.ModelChoiceField(
queryset=UserProfile.objects.filter(is_active=True)
label=_(u'User')
)
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
if user is not None:
self.fields['user'].queryset = UserProfile.objects.filter(
is_active=True, company__userprofile=user
)
class Meta:
model = Customer
fields = ('user',)
Then in the view you pass the logged in user:
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
if request.method == 'POST':
form = AssignForm(request.POST, request.FILES, user=request.user)
# …
else:
form = AssignForm(user=request.user)
# …
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad