Creating a JSON response using Django and Python

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

    In View use this:

    form.field.errors|striptags
    

    for getting validation messages without html

    0 讨论(0)
  • 2020-11-22 06:40

    Since Django 1.7 you have a standard JsonResponse that's exactly what you need:

    from django.http import JsonResponse
    ...
    return JsonResponse(array_to_js, safe=False)
    

    You don't even need to json.dump your array.

    0 讨论(0)
  • 2020-11-22 06:40
    from django.http import HttpResponse
    import json
    
    class JsonResponse(HttpResponse):
        def __init__(self, content={}, mimetype=None, status=None,
                 content_type='application/json'):
            super(JsonResponse, self).__init__(json.dumps(content), mimetype=mimetype,
                                               status=status, content_type=content_type)
    

    And in the view:

    resp_data = {'my_key': 'my value',}
    return JsonResponse(resp_data)
    
    0 讨论(0)
  • 2020-11-22 06:45

    You'll want to use the django serializer to help with unicode stuff:

    from django.core import serializers
    
    json_serializer = serializers.get_serializer("json")()
        response =  json_serializer.serialize(list, ensure_ascii=False, indent=2, use_natural_keys=True)
        return HttpResponse(response, mimetype="application/json")
    
    0 讨论(0)
  • 2020-11-22 06:49

    New in django 1.7

    you could use JsonResponse objects.

    from the docs:

    from django.http import JsonResponse
    return JsonResponse({'foo':'bar'})
    
    0 讨论(0)
  • 2020-11-22 06:49

    First import this:

    from django.http import HttpResponse
    

    If you have the JSON already:

    def your_method(request):
        your_json = [{'key1': value, 'key2': value}]
        return HttpResponse(your_json, 'application/json')
    

    If you get the JSON from another HTTP request:

    def your_method(request):
        response = request.get('https://www.example.com/get/json')
        return HttpResponse(response, 'application/json')
    
    0 讨论(0)
提交回复
热议问题