[Django]-How to get requested user in clean function in django forms?

4👍

You never construct a form with a request in the first place. You should pass this with:

class KycFormCreateView(CreateView):
    form_class = KycModelForm
    model = KycModel
    template_name = 'accounts/kyc/new_kyc.html'

    def get_form_kwargs(self, *args, **kwargs):
        form_kwargs = super().get_form_kwargs(*args, **kwargs)
        form_kwargs['request'] = self.request
        return form_kwargs
    
    def form_valid(self, form):
        user_kyc = form.save(commit=False)
        user_kyc.owner = self.request.user 
        user_kyc.save()
        return super().form_valid(form)

In the clean function, you do not need to query for a user self.request.user is a user object, so you can work with self.request.user directly:

class KycModelForm(forms.ModelForm):
    
    class Meta:
        model = KycModel
        fields = '__all__'
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(KycModelForm, self).__init__(*args, **kwargs)

     def clean(self):
        cleaned_data = super().clean()
        user = self.request.user
        print(user)
        return cleaned_data

Leave a comment