import re from django.http import HttpResponseRedirect from django.conf import settings from django.contrib.sites.models import Site class iPhoneMiddleware(object): def __init__(self): self.main_site = Site.objects.get(pk=1) self.mobile_site = Site.objects.get(pk=2) def process_request(self, request): if not request.session.get('mobile'): p = re.compile('iPhone|iPod', re.IGNORECASE) if p.search(request.META['HTTP_USER_AGENT']): request.session['mobile'] = True else: request.session['mobile'] = False return if not self.mobile_site == Site.objects.get_current(): if request.session.get('mobile'): return HttpResponseRedirect('http://%s%s' % (self.mobile_site.domain, request.path))