Adding a session to a Django request generated by RequestFactory

The Django RequestFactory is a useful tool for writing unit tests against Django views. I was using it to test some code that interacts with Cartridge, and ran into trouble because the RequestFactory doesn’t annotate request objects with Session objects, which is what Cartridge expects.

Turns out you can add the sessions by manually invoking the relevant middleware:

from django.contrib.sessions.middleware import SessionMiddleware
def add_session_to_request(request):
"""Annotate a request object with a session"""
middleware = SessionMiddleware()

view raw

hosted with ❤ by GitHub

Note that saving the session object seems to be required in order to generate the associated session_key field, which the Cartridge code was looking for.

This entry was posted in django and tagged . Bookmark the permalink.

6 Responses to Adding a session to a Django request generated by RequestFactory

  1. gcetusic says:

    Exactly what I needed!

  2. Excellent! how can we do it with mock ?

  3. Wayne Ye says:

    Solve the issue within 1 minute by reading this, thanks!

  4. Bogdan says:

    Very ty for this mock)

  5. JIBBER!!!! says:

    Nice one thanks. Still works in 2016!!

  6. bl4ckb1rd says:

    Thank you, Still works in 2018!!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s