When creating unit tests in Django, there are times when you need a Request (WSGIRequest).
There is something called django.test.RequestFactory
, which allows you to create requests. However, creating requests this way can be quite cumbersome, and since the requests created do not pass through the middleware, it can be challenging to use them for view-level tests.
Instead, using the test client to actually make requests to appropriate views is easier. The response returned contains a request property called wsgi_request
, which you can use. These requests have also passed through the middleware.
client = self.client_class()
response = client.post(...)
request = response.wsgi_request
Comments