简体   繁体   中英

how to return json response from views.py instead of .html file in django

I am working on django project that is returning a template in its views.py with context as: return render_to_response('page.html', context) here context is a dictionary that is having keys and values from multiple model classes

I need to just return the json response instead of html page. please help me out.

You can create a view that returns a JsonResponse :

from django.http import JsonResponse

def some_view(request):
    return {'some_key': 'some_value'}

(…) is a dictionary that is having keys and values from multiple model classes

You can simply pass model objects as JSON. In that case you need to serialize this properly. You can use Django's serialization framework , or work with aSerializer from the Django REST framework . The Django REST framework also offers a lot of tooling for CRUD operations with JSON or XML, etc.

You can use https://docs.djangoproject.com/en/3.2/ref/request-response/#jsonresponse-objects if you're only using Django.

But If you use drf you could use drf Response's. https://www.django-rest-framework.org/api-guide/views/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM