Ad

How To Get Current User In Forms?

- 1 answer

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
Ad