Change Django Templates Based on User-Agent Change Django Templates Based on User-Agent django django

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 reMOBILE_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'), ...)