How to access the HttpRequest object in Django forms

Passing the request object to the form

In your view, when you create a form instance, pass the request object as a parameter. Here I used a parameter named request.

form = MyForm(request.POST, request.FILES, request=request)

Accessing the request object in the form

In your form, use the __init__ method to assign the request object to a variable. Here I used self.request.

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(MyForm, self).__init__(*args, **kwargs)

Form validation

Now we can use the self.request variable to access the request object inside of our form methods.

In the following example, I used the self.request variable to check if the name of the currently logged user is different from the value of the ‘name’ field.

class MyForm(forms.ModelForm):
    # Use self.request in your field validation
    def clean_name(self):
        if self.cleaned_data['name'] != self.request.user.name:
            raise forms.ValidationError("The name is not the same.")
        return self.cleaned_data['name']