How can my Django views find out which template to display, or return JSON?

Our site can be accessed from a full browser, from mobile browsers and from a custom iPhone application. Since the logic is basically the same regardless of the client, we use the same views to handle all types of requests. But at the bottom of each of our views, we have something like:

if request.is_mobile(): return render_to_response('foo/bar/baz_mobile.html', context) elif request.is_api(): return json.dumps(context) else: return render_to_response('foo/bar/baz.html', context) 

Clearly there is a better way to do this :)

I thought that our views return a context dictionary and wrap them in a decorator that determines how to display the response. Alternatively, there might be something that I can do with class based views.

How do you do this?

+4
source share
3 answers

You have a function that returns a dict, and then has two kinds, one of which encodes it as JSON, and the other through a template.

+3
source

Ignacio Vasquez-Abrams is right.

As you said, the logic is basically the same, but logic is not viewing. According to the original MVC article: "A view is a (visual) representation of its model." Thus, you must have separate representations for different purposes, using the same logic.

+1
source

As described here:

http://docs.djangoproject.com/en/dev/ref/request-response/#attributes

So, including the request argument from your view into the context of your template:

 @auto_render def base_index(request, template_name="desktop-home.html") : user_agent = request.META["HTTP_USER_AGENT"] if "mobile" in user_agent : template_name = "mobile-home.html" return template_name, { "Navigation" : NavigationManager.db, "Headers" : request } 

So in your template:

 {{ Headers.META.HTTP_USER_AGENT }} 

What reports:

 Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Ubuntu/10.04 Chromium/8.0.552.237 Chrome/8.0.552.237 Safari/534.10 
0
source

Source: https://habr.com/ru/post/1300540/


All Articles