Tutorials  Articles  Notifications  Login  Signup


RK

Rajan Kumar

Founder at HackersFriend Aug. 11, 2020, 10:10 p.m. ⋅ 2752 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')

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account