Detect mobile, tablet or Desktop on Django

后端 未结 5 1447
终归单人心
终归单人心 2021-02-01 19:56

I need to detect 3 types of device: tablet, mobile or desktop.

I found a script for detecting mobile on github, but how I can det

5条回答
  •  灰色年华
    2021-02-01 20:28

    Based on your prior use of mobile detection middleware, I'd recommend the following:

    Pick up the Python port of MobileESP (source code here) and drop it into a folder named mobileesp in the base of your project (where manage.py is). Throw in a blank __init__.py file so that Python will see it as a package.

    Go ahead and create a new file, middleware.py, in that directory, and fill it with:

    import re
    from mobileesp import mdetect
    
    class MobileDetectionMiddleware(object):
        """
        Useful middleware to detect if the user is
        on a mobile device.
        """
        def process_request(self, request):
            is_mobile = False
            is_tablet = False
            is_phone = False
    
            user_agent = request.META.get("HTTP_USER_AGENT")
            http_accept = request.META.get("HTTP_ACCEPT")
            if user_agent and http_accept:
                agent = mdetect.UAgentInfo(userAgent=user_agent, httpAccept=http_accept)
                is_tablet = agent.detectTierTablet()
                is_phone = agent.detectTierIphone()
                is_mobile = is_tablet or is_phone or agent.detectMobileQuick()
    
            request.is_mobile = is_mobile
            request.is_tablet = is_tablet
            request.is_phone = is_phone
    

    Lastly, make sure to include 'mobileesp.middleware.MobileDetectionMiddleware', in MIDDLEWARE_CLASSES in your settings file.

    With that in place, in your views (or anywhere that you have a request object) you can check for is_phone (for any modern smartphones), is_tablet (for modern tablets) or is_mobile (for any mobile devices whatsoever).

提交回复
热议问题