How to check if a visitor is on a mobile device or a desktop with Django ?


For a website developped with django to check if a visitor is on a mobile device, a solution is to look at the visitor http_user_agent

Check vistor http_user_agent:

To check a vistor http_user_agent just enter in views:

user_agent = request.META['HTTP_USER_AGENT']

then if you take a look at user_agent:

print(user_agent)

you should get soemthing like for example:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) 
AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/**.*.****.***
Safari/537.36

Note that user_agent varibale is a string here:

print(type(user_agent))

returns:

str

After you can go to this link to get a list of mobile browser names.

Now to check if a vistor is on a mobile device just do for example

if 'Mobile' in user_agent:
    print('Visitor is on mobile')
else:
    print('Visitor is not on mobile')

which works for most of the mobile browser. Or create a list of keywords to check if a visitor is on mobile device:

keywords = ['Mobile','Opera Mini','Android']

user_agent = 'Mozilla/5.0 (Linux; Android 7.0; SAMSUNG SM-G955U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/5.4 Chrome/51.0.2704.106 Mobile Safari/537.36'

if any(word in user_agent for word in keywords):
    print('Visitor is on mobile device')
else:
    print('Visitor is on desktop')

returns for example

Visitor is on mobile device

References