Change Django Templates Based on User-Agent

imjoevasquez picture imjoevasquez · Oct 2, 2008 · Viewed 17.7k times · Source

I've made a Django site, but I've drank the Koolaid and I want to make an IPhone version. After putting much thought into I've come up with two options:

  1. Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.
  2. Find some time of middleware that reads the user-agent, and changes the template directories dynamically.

I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation discourages changing settings on the fly. I found a snippet that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.

Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?

Update

I went with a combination of middleware and tweaking the template call.

For the middleware, I used minidetector. I like it because it detects a plethora of mobile user-agents. All I have to do is check request.mobile in my views.

For the template call tweak:

 def check_mobile(request, template_name):
     if request.mobile:
         return 'mobile-%s'%template_name
     return template_name

I use this for any view that I know I have both versions.

TODO:

  • Figure out how to access request.mobile in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')
  • Using the previous automagically fallback to the regular template if no mobile version exists.

Answer

Aaron picture Aaron · Oct 2, 2008

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.