How do I return JSON without using a template in Django

+1 vote

I have a command line Python API for a Django app. When I access the app through the API it should return JSON and with a browser it should return HTML. I can use different URLs to access the different versions but how do I render the HTML template and JSON in the views.py with just one template?

To render the HTML I would use:

return render_to_response('sample/sample.html....')

But how would I do the same for JSON without putting a JSON template? (the content-type should be application/json instead of text/html)

What would determine the JSON and HTML outputs?

So in my views.py:

if something:
    return render_to_response('html_template',.....)
else:
    return HttpReponse(jsondata,mimetype='application/json')
Jul 3, 2020 in Python by kartik
• 37,520 points
4,875 views

1 answer to this question.

0 votes

Hello @kartik,

In the case of the JSON response there is no template to be rendered. Templates are for generating HTML responses. The JSON is the HTTP response.

However, you can have HTML that is rendered from a template withing your JSON response.

html = render_to_string("some.html", some_dictionary)
serialized_data = simplejson.dumps({"html": html})
return HttpResponse(serialized_data, mimetype="application/json")

Hope it works!!

Thank you!!

answered Jul 3, 2020 by Niroj
• 82,840 points

Related Questions In Python

0 votes
1 answer

how do i print only the last two letters in a string using regular expression in python?

$ to match the end of the ...READ MORE

answered Mar 15, 2019 in Python by Waseem
• 4,540 points
950 views
0 votes
1 answer

How do I create a dataframe using a dictionary in pandas?

Hi @Hannah, You need to define your dictionary ...READ MORE

answered Nov 18, 2019 in Python by Eric
798 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
2,510 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
1,586 views
0 votes
1 answer

How to do math in a Django template?

Hello @kartik, You can use the add filter: {{ object.article.rating_score|add:"-100" }} Thank ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
6,562 views
+1 vote
1 answer

How do I create a slug in Django?

Hello @kartik, You will need to use the ...READ MORE

answered Jun 26, 2020 in Python by Niroj
• 82,840 points
1,278 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP