Carlos Roso
Carlos Roso

Reputation: 1495

How to handle web and mobile requests in django view

I know this is a pretty simple question, but I haven't understood how to tackle this problem.

I have a model called Restaurant with information about a restaurant (name, location, etc). I have a view that handles requests to the url localhost:8000/restaurants and returns a JSON representation of the restaurants using django-rest-framework. I've made it this way because I'm consuming this data from an android app.

Now I want to access the same url from the web, but this time I want to see a fully rendered html with the restaurants' info.

So, my specific question is, how can I know (and consequently responds with a JSON stream or html) whether the request is coming from the android app or from a web browser if both requests are pointed to the same url and view?

Upvotes: 1

Views: 1025

Answers (2)

Sudip Kafle
Sudip Kafle

Reputation: 4391

You can use Django Rest Framework's TemplateHTMLRenderer. It conditionally outputs either JSON or HTML page based on the type of request. You can define the following attributes for the View that you are using

class YourView(generics.TypOfView):
    renderer_classes = (TemplateHTMLRenderer, JSONRenderer,)
    template_name = 'path_to_template.html'

Upvotes: 1

dev4Fun
dev4Fun

Reputation: 1050

I can not comment yet, so I will post it in the answer.

You might want to try to create the middleware as described by Adam here, and in your views you can perform checking with is_phone, is_tablet and then send response in appropriate format

Upvotes: 0

Related Questions