[Django App] django-user-agents

[설치]

pip install pyyaml ua-parser user-agents
pip install django-user-agents


[설정]

settings.py 수정

INSTALLED_APPS = (
    # Other apps...
    'django_user_agents',
)

MIDDLEWARE = (
    # other middlewares...
    'django_user_agents.middleware.UserAgentMiddleware',
)

django-user-agents Settings

# Cache backend is optional, but recommended to speed up user agent parsing
# CACHES = {
#    'default': {
#        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
#        'LOCATION': '127.0.0.1:11211',
#    }
# }

# Name of cache backend to cache user agents. If it not specified default
# cache alias will be used. Set to `None` to disable caching.
USER_AGENTS_CACHE = 'default'


[소스 활용]

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'


[IF문 활용]

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


[View 활용]

from django_user_agents.utils import get_user_agent

def my_view(request):
    user_agent = get_user_agent(request)
    if user_agent.is_mobile:
        # Do stuff here...
    elif user_agent.is_tablet:
        # Do other stuff...


[Template 활용]

{% 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 %}

{% if request|is_touch_capable %}
    Touch capable device stuff...
{% endif %}

{% if request|is_bot %}
    Bot stuff...

{% endif %}

댓글

이 블로그의 인기 게시물

[Django Install] 9.1 sc제일은행 nginx-django 연결

[Django APP] django-widget-tweaks