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:
In View use this:
form.field.errors|striptags
for getting validation messages without html
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.
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)
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")
New in django 1.7
you could use JsonResponse objects.
from the docs:
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
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')