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.

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.

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.

  • Ursomniac

    Ditto — how does this work with the Django Admin?

  • Виталик

    Hi, How can i use this form in admin site?