Tuesday, November 5, 2013

Creating Mobile Webpages with Django

Supporting both mobile and desktop browsers is an important part of any live website. A mobile webpage should be simpler and display the bare minimum of necessary information in a small space. Frameworks like ASP.NET MVC 4 have built in features that allow for detection of mobile devices so you can display different pages depending on how the site is being viewed. I wanted to look at some options for doing this in Django.

Django-mobile 0.3.0

This package is easy to install and doesn't require many steps to be used. Once working it adds a property to request object called flavour that you can query to see if its coming from a mobile device or not. The package can be found here. Setup is easy as described on the page itself. I used pip to install it and then added the necessary changes to settings.py:

TEMPLATE_LOADERS = (
    'django_mobile.loader.Loader',
    ...

TEMPLATE_CONTEXT_PROCESSORS = (
    'django_mobile.context_processors.flavour',
)

MIDDLEWARE_CLASSES = (
    ...
    'django_mobile.middleware.MobileDetectionMiddleware',
    'django_mobile.middleware.SetFlavourMiddleware',

INSTALLED_APPS = (
    ...
    'django_mobile',

Now when defining our function in views.py, we can simply look for the new property and pass it on.

def home(request):
  mobilePage = 0
  if request.flavour == "mobile":
    mobilePage = 1

  ...
  context = { 'mobilePage': mobilePage }
  return render(request, 'home', context)

Now we can use the property in our template. We can render custom tags inside the control statements to change the whole experience of the page based on the device:

<html>
<body>
    {% if mobilePage == 1 %}
    Welcome to the mobile version.
    {% else %}
    Welcome to the regular version.
    {% endif %}
</body>
</html>

Django-mobi

Another easy to use package is called Django-mobi and can be found here. Simply put the package inside your project and you can easily reference it in your code using an attribute. A bonus to this package is that it has the ability to exempt certain devices from being detected as described on their home page. To use the package we just need to add it to settings.py:

MIDDLEWARE_CLASSES = (
    ...
    'mobi.MobileDetectionMiddleware',
Now we can use it in our code. In practice, it works just like the example above:

from mobi.decorators import detect_mobile
...
@detect_mobile
def home(request):
    mobilePage = 0
    if request.mobile:
        mobilePage = 1

    context = { 'mobilePage': mobilePage }
    return render(request, 'home', context)
These are two decent options I found for customizing Django sites. There could be other ways as well but I felt these worked pretty nicely.

1 comment:

  1. Excellent article.
    Do you have updates for Django-mobile new version 0.6.0 on Python 2.7/Django 1.8?

    ReplyDelete