[Django]-Detect mobile devices with Django and Python 3

44👍

Django User Agents package is compatible with Python 3.

Follow the installation instructions in the link provided above and then you can use it as follows:

def my_view(request):

    # Let's assume that the visitor uses an iPhone...
    request.user_agent.is_mobile # returns True
    request.user_agent.is_tablet # returns False
    request.user_agent.is_touch_capable # returns True
    request.user_agent.is_pc # returns False
    request.user_agent.is_bot # returns False

    # Accessing user agent's browser attributes
    request.user_agent.browser  # returns Browser(family=u'Mobile Safari', version=(5, 1), version_string='5.1')
    request.user_agent.browser.family  # returns 'Mobile Safari'
    request.user_agent.browser.version  # returns (5, 1)
    request.user_agent.browser.version_string   # returns '5.1'

    # Operating System properties
    request.user_agent.os  # returns OperatingSystem(family=u'iOS', version=(5, 1), version_string='5.1')
    request.user_agent.os.family  # returns 'iOS'
    request.user_agent.os.version  # returns (5, 1)
    request.user_agent.os.version_string  # returns '5.1'

    # Device properties
    request.user_agent.device  # returns Device(family='iPhone')
    request.user_agent.device.family  # returns 'iPhone'

The usage in template is as follows:

{% if request.user_agent.is_mobile %}
    Do stuff here...
{% endif %}

However, note that the middleware class has changed in Django 1.10. So if you are using Django 1.10 +, you will have to modify the middleware class definition in this Package as given in this GitHub issue tracker page.

31👍

I found an alternative way, starting from this answer.

By adding an additional function into views.py:

import re

def mobile(request):
"""Return True if the request comes from a mobile device."""

    MOBILE_AGENT_RE=re.compile(r".*(iphone|mobile|androidtouch)",re.IGNORECASE)

    if MOBILE_AGENT_RE.match(request.META['HTTP_USER_AGENT']):
        return True
    else:
        return False


def myfunction(request):

    ...
    if mobile(request):
        is_mobile = True
    else:
        is_mobile = False

    context = {
        ... ,
        'is_mobile': is_mobile,
    }
    return render(request, 'mytemplate.html', context)
👤J0ANMM

Leave a comment