0

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.

2 Answers 2

6

You can create a view that returns a JsonResponse:

from django.http import JsonResponse

def some_view(request):
    return JsonResponse({'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 a Serializer from the Django REST framework. The Django REST framework also offers a lot of tooling for CRUD operations with JSON or XML, etc.

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.