Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango - detect mobile device in views
    text
    copied!<p>I am already using a device detection (<a href="http://djangosnippets.org/snippets/2228/" rel="noreferrer">http://djangosnippets.org/snippets/2228/</a>) in my templates and trying to also make it work in views, so i can redirect to the app store if a user comes from an iPhone.</p> <p>So I already had:</p> <pre><code>import re def mobile(request): device = {} ua = request.META.get('HTTP_USER_AGENT', '').lower() if ua.find("iphone") &gt; 0: device['iphone'] = "iphone" + re.search("iphone os (\d)", ua).groups(0)[0] if ua.find("ipad") &gt; 0: device['ipad'] = "ipad" if ua.find("android") &gt; 0: device['android'] = "android" + re.search("android (\d\.\d)", ua).groups(0)[0].translate(None, '.') # spits out device names for CSS targeting, to be applied to &lt;html&gt; or &lt;body&gt;. device['classes'] = " ".join(v for (k,v) in device.items()) return {'device': device } </code></pre> <p>And then created a class in tools/middleware.py:</p> <pre><code>from tools.context_processor import mobile class detect_device(object): def process_request(self, request): device = mobile(request) request.device = device </code></pre> <p>Added the following to MIDDLEWARE_CLASSES in the settings.py:</p> <pre><code>'tools.middleware.detect_device' </code></pre> <p>And in views.py I created:</p> <pre><code>def get_link(request): if request.device.iphone: app_store_link = settings.APP_STORE_LINK return HttpResponseRedirect(app_store_link) else: return HttpResponseRedirect('/') </code></pre> <p>But I am getting the error: </p> <blockquote> <p>'dict' object has no attribute 'iphone'</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload