Y
Y
yabivipil2015-09-08 18:00:06
Django
yabivipil, 2015-09-08 18:00:06

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

2 answer(s)
M
marazmiki, 2015-09-08
@yabivipil

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.

D
devel787, 2015-09-10
@devel787

There is a battery https://github.com/gregmuellegger/django-mobile
Perhaps the sources will help you with something.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question