Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Django Templates Based on User-Agent

Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render_to_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the standard html version if they are using an iphone.


Detect the user agent in middleware, switch the url bindings, profit!

How? Django request objects have a .urlconf attribute, which can be set by middleware.

From django docs:

Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has an attribute called urlconf (set by middleware request processing), its value will be used in place of the ROOT_URLCONF setting.

  1. In yourproj/middlware.py, write a class that checks the http_user_agent string:

    import re
    MOBILE_AGENT_RE=re.compile(r".*(iphone|mobile|androidtouch)",re.IGNORECASE)
    class MobileMiddleware(object):
        def process_request(self,request):
            if MOBILE_AGENT_RE.match(request.META['HTTP_USER_AGENT']):
                request.urlconf="yourproj.mobile_urls"
    
  2. Don't forget to add this to MIDDLEWARE_CLASSES in settings.py:

    MIDDLEWARE_CLASSES= [...
        'yourproj.middleware.MobileMiddleware',
    ...]
    
  3. Create a mobile urlconf, yourproj/mobile_urls.py:

    urlpatterns=patterns('',('r'/?$', 'mobile.index'), ...)
    

I'm developing djangobile, a django mobile extension: http://code.google.com/p/djangobile/


You should take a look at the django-mobileadmin source code, which solved exactly this problem.


Other way would be creating your own template loader that loads templates specific to user agent. This is pretty generic technique and can be use to dynamically determine what template has to be loaded depending on other factors too, like requested language (good companion to existing Django i18n machinery).

Django Book has a section on this subject.


There is a nice article which explains how to render the same data by different templates http://www.postneo.com/2006/07/26/acknowledging-the-mobile-web-with-django

You still need to automatically redirect the user to mobile site however and this can be done using several methods (your check_mobile trick will work too)


How about redirecting user to i.xxx.com after parsing his UA in some middleware? I highly doubt that mobile users care how url look like, still they can access your site using main url.