Django User Agents
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
- breaking For Django versions 1.10 and later, you must use the `MIDDLEWARE` setting instead of the deprecated `MIDDLEWARE_CLASSES`. Failing to do so will prevent the `UserAgentMiddleware` from being active and `request.user_agent` will not be available.
- gotcha The prerequisite packages `pyyaml`, `ua-parser`, and `user-agents` must be installed *before* `django-user-agents`. Not installing these dependencies first will lead to `ModuleNotFoundError` or other import errors when `django-user-agents` attempts to load them.
- gotcha Caching user agent parsing results is optional but strongly recommended for performance, especially under high traffic. Without caching configured, the library will re-parse the user agent string on every request, which can introduce unnecessary overhead.
- gotcha User-Agent strings are provided by the client and can be easily spoofed. Do not rely solely on `request.user_agent` properties for security-sensitive operations or critical business logic where precise, unforgeable client identification is required.
- deprecated The `0.4.0` release was published in June 2019, officially supporting Python up to 3.7 and Django up to 2.2. While it might still function with newer Python (3.8+) or Django (3.0+) versions due to backward compatibility, official support and testing for these newer environments are not guaranteed. Users should test thoroughly for compatibility if using modern Python/Django.
Install
-
pip install pyyaml ua-parser user-agents -
pip install django-user-agents
Imports
- UserAgentMiddleware
from django_user_agents.middleware import UserAgentMiddleware
- get_user_agent
from django_user_agents.utils import get_user_agent
Quickstart
# 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)