Change Django Templates Based on User-Agent

前端 未结 10 2539
耶瑟儿~
耶瑟儿~ 2020-12-07 11:37

I\'ve made a Django site, but I\'ve drank the Koolaid and I want to make an IPhone version. After putting much thought into I\'ve come up with two options:

10条回答
  •  佛祖请我去吃肉
    2020-12-07 11:49

    Detect the user agent in middleware, switch the url bindings, profit!

    How? Django request objects have a .urlconf attribute, which can be set by middleware.

    From django docs:

    Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has an attribute called urlconf (set by middleware request processing), its value will be used in place of the ROOT_URLCONF setting.

    1. In yourproj/middlware.py, write a class that checks the http_user_agent string:

      import re
      MOBILE_AGENT_RE=re.compile(r".*(iphone|mobile|androidtouch)",re.IGNORECASE)
      class MobileMiddleware(object):
          def process_request(self,request):
              if MOBILE_AGENT_RE.match(request.META['HTTP_USER_AGENT']):
                  request.urlconf="yourproj.mobile_urls"
      
    2. Don't forget to add this to MIDDLEWARE_CLASSES in settings.py:

      MIDDLEWARE_CLASSES= [...
          'yourproj.middleware.MobileMiddleware',
      ...]
      
    3. Create a mobile urlconf, yourproj/mobile_urls.py:

      urlpatterns=patterns('',('r'/?$', 'mobile.index'), ...)
      

提交回复
热议问题