Answer the question
In order to leave comments, you need to log in
How to make midleware in django that changes TEMPLATE_DIRS?
We need to make a mobile version for the site. I decided in the middleware to determine whether it is a mobile phone and, depending on this, substitute the desired template.
However, when I click on the URL, I get the old templates.
I am using django1.7 and python 3.
class DetectMobileBrowser():
def process_request(self, request):
if request.META.get('HTTP_USER_AGENT'):
user_agent = request.META['HTTP_USER_AGENT']
.....
if mobile:
settings.TEMPLATE_DIRS = settings.MOBILE_TEMPLATE_DIRS
else:
settings.TEMPLATE_DIRS = settings.DESKTOP_TEMPLATE_DIRS
Answer the question
In order to leave comments, you need to log in
When you do this kind of thing, keep in mind that the settings object is global. When you log in from the mobile version, the middleware will change TEMPLATE_DIRS. And right after you (before janga had time to start rendering the template) - someone from the computer. And the value of TEMPLATE_DIRS will return to its original value.
The keyword for finding a solution is thread locals.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question