Django Hack: How to access request object from models

Ruhshan Ahmed Abir
Feb 19, 2018 · 1 min read

Django has some standard practices of organizing codes. It appreciates separating different contextual codes and classes in different files and modules. Of course there are good reasons behind this kind of compartmentalization. You still can mix something easily, like you can write a form class within a view, and something you can’t easily like access request object from model. But sometimes you need to break the boundaries for experiment or fun.

In my case to expose request object in model, I first initialized and empty variable in . I wrote a middleware that upon calling copies the request object in the empty variable in

Suppose you app name is demoapp, now create an empty variable exposed_request inside the of demoapp. Then in the apps directory create a new python file and give a meaningfull name like where you will write your middleware codes like this:

Now open your At the middleware list, append this line:


That’s it, now you can access django’s request object as exposed_request from and can do whatever you wanted to do.