use JsonResponse instead of HttpResponse to send JSON data

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

Metadata

ID: python-django/http-response-with-json-dumps

Language: Python

Severity: Notice

Category: Best Practices

Description

Use JsonResponse instead of HttpResponse when attempting to send JSON data.

Non-Compliant Code Examples

import json

from django.http import HttpResponse

response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'
return HttpResponse(json.dumps(response_data))  # use a JsonResponse to send JSON data

Compliant Code Examples

from django.http import JsonResponse

response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'
return JsonResponse(response_data)
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis