Home > Software engineering >  How to get current user in forms?
How to get current user in forms?

Time:03-17

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?

CodePudding user response:

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)
    # …

CodePudding user response:

You have to pass the request.user from views.py in order to get it in the form. In your form write this __init__ function and pass the user from your views.py and you can get the user. You can access the user as self.user in your form

class AssignForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.get('user')
        kwargs.pop('user')

In your views.py call the form like below

form = AssignForm(user=request.user)
  • Related