RK

rajan

Founder & Programmer at HackersFriend Aug. 11, 2020, 10:10 p.m. ⋅ 133 views

How to return JSON Encoded response from Django View


From django 1.7 + we have built-in JsonResponse in Django. It sets Content-Type in http header to application/json, and converts the data to json also.

See the example below:

from django.http import JsonResponse

def profile(request):
    data = {
        'Company': 'HackersFriend',
        'location': 'India',
    }
    return JsonResponse(data)

If your data is not a dictionary you need to pass safe = False.

return JsonResponse([1, 2, 3, 4], safe=False)

We can also fetch data from any Django model and return it as json in response from any view.

def get_articles(request):
    articles = Article.objects.all().values('title', 'content')  # or put just .values() to get all fields
    articles_list = list(articles)  # we must convert the QuerySet to a list object
    return JsonResponse(articles_list, safe=False)

 

We can also do return Json response manually using HttpResponse object.

import json
from django.http import HttpResponse

def profile(request):
    data = {
        'company': 'HackersFriend',
        'location': 'India',
    }
    dump = json.dumps(data)
    return HttpResponse(dump, content_type='application/json')

 



Go back to feed

HackersFriend Updates





View more


Events


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details


Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details