Creating a JSON response using Django and Python

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

    Its very convenient with Django version 1.7 or higher as you have the JsonResponse class, which is a subclass of HttpResponse.

    from django.http import JsonResponse
        def profile(request):
            data = {
                'name': 'Raghav',
                'location': 'India',
                'is_active': False,
                'count': 28
            }
            return JsonResponse(data)
    

    For older versions of Django, you must use an HttpResponse object.

    import json
    from django.http import HttpResponse
    
    def profile(request):
        data = {
            'name': 'Raghav',
            'location': 'India',
            'is_active': False,
            'count': 28
        }
        dump = json.dumps(data)
        return HttpResponse(dump, content_type='application/json')
    

提交回复
热议问题