Categories
Python Answers

How to access the request object or any other variable in a form’s clean() method with Python Django?

Spread the love

To access the request object or any other variable in a form’s clean() method with Python Django, we can use self.request in the clean method to access the request object.

For instance, we write

class MyForm(forms.Form):

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


    def clean(self):
        self.request
        # ...  

to create the MyForm form with the clean method.

And then we can use self.request to access the request object in the clean method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *