N
N
niko832011-09-01 13:36:32
Django
niko83, 2011-09-01 13:36:32

How to get the request object from any part of the code in Django?

The request object is passed to view.py.
What to do when we need to access this object, for example, in a model, in some of our modules, or somewhere else.
At the same time, you do not want to always pass this object as an argument.
It would be desirable to have the guaranteed direct access.
Perhaps in Django the Registry pattern is organized, where you can always refer to this object?
Or is there some other way to get to it.
And if you organize the Registry pattern on your own, in which part when should the request object be registered in our registry?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
enchantner, 2011-09-01
@niko83

Global variables are evil. In general, ideally, you have views and middleware to solve all problems, the request should not appear in models at all, this is from the evil one. MVC is everything.

Y
Yngvie, 2011-09-01
@Yngvie

In the same article, a link to which bekbulatov gave, there was a solution, but it was removed from there in favor of passing request as a parameter.
You can look at the previous version . It uses Middleware for global access to the user object, but it will not be difficult to convert it to request.
It’s worth using not when “you don’t want to always pass this object as an argument”, but when there is simply no such possibility.
And do not forget that the code can be called not only from the view, but also, say, from the management command or the console.

B
bekbulatov, 2011-09-01
@bekbulatov

Developers recommend passing request as an argument. Here about the cons of using threadlocals

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question