Django User Agents

0.4.0 · active · verified Mon Apr 13

A Django package that allows easy identification of visitors' browser, operating system, and device information (mobile phone, tablet, or touch capabilities). It uses the `user-agents` library under the hood. The current version is 0.4.0.

Warnings

Install

Imports

Quickstart

To use `django-user-agents`, first add `django_user_agents` to your `INSTALLED_APPS` and `UserAgentMiddleware` to your `MIDDLEWARE` setting. Once configured, a `user_agent` attribute will be automatically added to the `request` object, providing properties like `is_mobile`, `is_tablet`, `is_pc`, and details about the browser and OS. Caching is optional but highly recommended for performance. You can also manually get a `UserAgent` instance using `get_user_agent(request)`.

# settings.py
INSTALLED_APPS = [
    # ... other apps
    'django_user_agents',
]

MIDDLEWARE = [
    # ... other middleware
    'django_user_agents.middleware.UserAgentMiddleware',
]

# Optional: Recommended for performance
# CACHES = {
#     'default': {
#         'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
#         'LOCATION': 'unique-snowflake',
#     }
# }
# USER_AGENTS_CACHE = 'default'

# views.py
from django.shortcuts import render
from django_user_agents.utils import get_user_agent

def my_view(request):
    # Access via request.user_agent (if middleware is used)
    is_mobile = request.user_agent.is_mobile
    is_tablet = request.user_agent.is_tablet
    is_pc = request.user_agent.is_pc
    browser_family = request.user_agent.browser.family

    # Alternatively, get it explicitly
    # user_agent = get_user_agent(request)
    # is_bot = user_agent.is_bot

    context = {
        'is_mobile': is_mobile,
        'is_tablet': is_tablet,
        'is_pc': is_pc,
        'browser_family': browser_family,
    }
    return render(request, 'my_template.html', context)

view raw JSON →