Home >Backend Development >Python Tutorial >How to Correctly Construct JSON Responses in Django?

How to Correctly Construct JSON Responses in Django?

DDD
DDDOriginal
2024-11-25 21:11:12857browse

How to Correctly Construct JSON Responses in Django?

Creating JSON Responses with Django and Python

In Django, converting server-side Ajax responses to Django HttpResponse can be straightforward if done correctly. Let's explore a previous attempt and its pitfalls.

The Converted Code

The original code in question attempted to convert a server-side script into a Django HttpResponse:

def validate_user(request):
    if request.method == 'POST':
        ...
        array_to_js = [vld_id, vld_error, False]

        if vld_value == "TestUser":
            array_to_js[2] = True
            x = simplejson.dumps(array_to_js)
            return HttpResponse(x)
        else:
            ...
            return render_to_response('index.html', ...)

The Issue

The issue lies in using a list (array_to_js) to construct the JSON response. Django expects a dictionary when creating JSON responses.

The Solution

To resolve this, use a dictionary to store the response data:

response_data = {}
response_data['vld_id'] = vld_id
response_data['vld_error'] = vld_error
response_data['valid'] = False

if vld_value == "TestUser":
    response_data['valid'] = True

json_response = json.dumps(response_data)
return HttpResponse(json_response, content_type="application/json")

Additional Tip

For Django 1.7 , you can use the JsonResponse class to easily create JSON responses:

from django.http import JsonResponse

return JsonResponse({
    'vld_id': vld_id,
    'vld_error': vld_error,
    'valid': False
})

The above is the detailed content of How to Correctly Construct JSON Responses in Django?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn