Creating a JSON response using Django and Python

后端 未结 15 2362
温柔的废话
温柔的废话 2020-11-22 06:02

I\'m trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it\'s not working.

This is the server-side script:



        
15条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 06:50

    I usually use a dictionary, not a list to return JSON content.

    import json
    
    from django.http import HttpResponse
    
    response_data = {}
    response_data['result'] = 'error'
    response_data['message'] = 'Some error message'
    

    Pre-Django 1.7 you'd return it like this:

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

    For Django 1.7+, use JsonResponse as shown in this SO answer like so :

    from django.http import JsonResponse
    return JsonResponse({'foo':'bar'})
    

提交回复
热议问题