Aoof
Aoof

Reputation: 332

How to get the Operating System of the user using Django?

I followed this guide trying to get user agent from request

specifically the Operating System Obviously I cannot use the normal way of getting the operating system which is using the os module with python but that won't work because the operating system will be the one hosting the server

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPALTES_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'myproject.myapp.context_processors.user_agent',
            ],
        },
    },
]

cannot do that. it claims that I don't have a myproject.myapp module

Upvotes: 2

Views: 1647

Answers (1)

Lomtrur
Lomtrur

Reputation: 1798

To get the user agent from a request you can use this in a view:

agent = request.META["HTTP_USER_AGENT"]

Then you can use something like httpagentparser to get the OS:

import httpagentparser
agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
s = httpagentparser.detect(agent)["os"]

Upvotes: 5

Related Questions