Reputation: 23
I am trying to send the JSON Format with added headers in .csv format to a front end for download. While sending a HTTP Response I am facing an "is not JSON serializable" error.
My views.py
file:
from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponse
import json as simplejson
import random
import csv
def DownloadEventLog(request):
downloadeventlog = "[{\"severity\":\"0\",\"description\":\"USB Connected\",\"date\":\"01/01/2015\",\"time\":\"11:35:20\"},{\"severity\":\"3\",\"description\":\"USB Disconnected\",\"date\":\"01/01/2015\",\"time\":\"10:30:19\"}]";
data = simplejson.loads(downloadeventlog)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="eventlog.csv"'
writer = csv.writer(response)
writer.writerow(data[0].keys())
for row in data:
writer.writerow(row.values())
print response
return HttpResponse(simplejson.dumps(response), content_type = "application/json")
Print response cmd is printing:
Content-Type: text/csv
Content-Disposition: attachment; filename="eventlog.csv"
date,time,severity,description
01/01/2015,11:35:20,0,"USB Connected"
02/02/2015,10:30:19,3,"USB Disconnected"
However the last line is throwing an error as follows:
TypeError at /eventlog/downloadeventlog
<django.http.response.HttpResponse object at 0x9c059ec>is not JSON serializable
Request Method: POST
Request URL: http://127.0.0.1:8001/eventlog/downloadeventlog
Django Version: 1.7.1
Python Version: 2.7.3
Upvotes: 1
Views: 1574
Reputation: 2834
simplejson and json don't work with django objects well.
Django's built-in serializers can only serialize querysets filled with django objects:
**** To use ****
data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, mimetype="application/json")
Hope that helps
Upvotes: 4
Reputation: 4838
You can just return the response
, you do not need the wrap it in HttpResponse
.
return response
Upvotes: 3
Reputation: 2103
You should use django's serializers here:
https://docs.djangoproject.com/en/dev/topics/serialization/
related question here:
<Django object > is not JSON serializable
Upvotes: 1