Home >Backend Development >Python Tutorial >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!