Archive for the ‘iPhone’ Tag

Different templates for iPhone/iPod in Django

I use this Django Middleware for detecting iPhones or iPods and for setting the template directory dynamically. If the user agent is an iPhone or iPod, the template directory is changed, so that different templates for the iProducts can be used. The idea is taken from this snippet, but it only detects iPhones and I had some troubles with caching so I wrote one myself.

from django.conf import settings
import re

class iPhoneMiddleware(object):
    """
    If the Middleware detects an iPhone/iPod the template dir changes to the
    iPhone template folder.
    """

    def __init__(self):
        self.normal_templates = settings.TEMPLATE_DIRS
        self.iphone_templates = (settings.TEMPLATE_DIRS[0] + '/iphone',)

    def process_request(self, request):
        p = re.compile('iPhone|iPod', re.IGNORECASE)
        if p.search(request.META['HTTP_USER_AGENT']):
            # user agent looks like iPhone or iPod
            settings.TEMPLATE_DIRS = self.iphone_templates
        else:
            # other user agents
            settings.TEMPLATE_DIRS = self.normal_templates
        return