Login

Detect iPhone & Switch Template via render_to_response

Author:
bryanhelmig
Posted:
May 23, 2010
Language:
Python
Version:
1.2
Score:
-2 (after 2 ratings)

A fast way to implement an iPhone template switcher, especially if you have a lot of existing views using the render_to_response() shortcut. This checks for the iPhone browser and then modifies the chosen template by adding -mobile to the html's file name.

Check out this more complete list of user agents if you need to detect specific mobile devices.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django.shortcuts import render_to_response as render_to_response_pre

def render_to_response(template, context):
    '''
    If the exisiting view uses a template named foo.html, any iPhone
    will trigger the template named foo-iphone.html.
    '''
    if 'HTTP_USER_AGENT' in context['request'].META:
        if 'iphone' in context['request'].META['HTTP_USER_AGENT'].lower():
            template = template.rstrip('.html')
            template += '-iphone.html'
    return render_to_response_pre(template, context)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.