Django Request Factory
Till now, we have been using Django's test client to test the views we have created for our application. The test client class simulates a browser and uses this simulation to make calls to the required APIs. But what if we did not want to use the test client and its associated simulation of being a browser, but rather wanted to test the view functions directly by passing the request parameter? How can we do that?
To help us in such cases, we can leverage the RequestFactory
class provided by Django. The RequestFactory
class helps us provide the request
object, which we can pass to our view functions to evaluate their working. The following object for RequestFactory
can be created by instantiating the class as follows:
factory = RequestFactory()
The factory
object thus created supports only HTTP methods such as get()
, post()
, put()
, and others, to simulate a call to any URL endpoint. Let us look at how we can modify the test case that we wrote in...