Creating a JSON response using Django and Python

后端 未结 15 2163
温柔的废话
温柔的废话 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:51

    I use this, it works fine.

    from django.utils import simplejson
    from django.http import HttpResponse
    
    def some_view(request):
        to_json = {
            "key1": "value1",
            "key2": "value2"
        }
        return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
    

    Alternative:

    from django.utils import simplejson
    
    class JsonResponse(HttpResponse):
        """
            JSON response
        """
        def __init__(self, content, mimetype='application/json', status=None, content_type=None):
            super(JsonResponse, self).__init__(
                content=simplejson.dumps(content),
                mimetype=mimetype,
                status=status,
                content_type=content_type,
            )
    

    In Django 1.7 JsonResponse objects have been added to the Django framework itself which makes this task even easier:

    from django.http import JsonResponse
    def some_view(request):
        return JsonResponse({"key": "value"})
    

提交回复
热议问题