User agent in Django | find if user is using mobile or PC or tablet | template & view usage in Django

User agent is a django package that allows easy identification of visitor’s browser, OS and device information, including whether the visitor uses a mobile phone, tablet or a touch capable device.

To install User agent in Django , run below two commands –

pip install django-user-agents

Than you have to mention it in settings.py file, INSTALLED_APPS section like –

INSTALLED_APPS = [
    'django.contrib.admin',
     ......
    'django_user_agents',
]

Than you have to mention it in MIDDLEWARE like –

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
     .......
    'django_user_agents.middleware.UserAgentMiddleware',
]

Use in views.py file –

def my_view(request):
    user_agent = get_user_agent(request)
    if user_agent.is_mobile:
        return HttpResponse('User using mobile')
    elif user_agent.is_pc:
        vi=request.META['HTTP_USER_AGENT']
        print(vi)
        return HttpResponse('User using Computer')

We can apply if condition as to know , what user is using mobile , tablet or laptop.

Use in templates –

{% load user_agents %}

{% if request|is_mobile %}
    Mobile device stuff...
{% endif %}

{% if request|is_tablet %}
    Tablet stuff...
{% endif %}

{% if request|is_pc %}
    PC stuff...
{% endif %}

We can apply if condition as to know , what user is using mobile , tablet or laptop.