Django Hack: How to access request object from models

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 models.py . I wrote a middleware that upon calling copies the request object in the empty variable in models.py.

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

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

'demoapp.request_exposer.RequestExposerMiddleware'

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

Like what you read? Give Ruhshan Ahmed Abir a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.