2

I'm using DJango 1.8 and Python 3.4

When the below view is being ran, Django throws Type Error - Object is not JSON Serializable

Views.py

from django.http import HttpRequest,HttpResponse
from django.http import JsonResponse
from json import dumps

def get_stats(request):
    if request.method == "POST":
        srch_dropV = request.POST['srch_dropAJ']
    else:
        srch_dropV = ''
    if(srch_dropV == 'Green'):
        students = GreenBased.objects.all()
    if(srch_dropV == 'Yellow'):
        students = YellowBased.objects.all()
    response_data = {}
    try:
        response_data['result'] = 'Success'
        response_data['message'] = list(students)
    except:
        response_data['result'] = 'Ouch!'
        response_data['message'] = 'Script has not ran correctly'
    return HttpResponse(JsonResponse(response_data), content_type="application/json")

I'm trying to read couple of rows from mysql database and display it on the html file, I'm facing below error message when above view is being ran

TypeError: YellowBased: YelloBased object is not JSON serializable

In HTML Page, I have a drop down list.. based on the option that is selected, my Ajax would return me the records that were fetched from mysql table.

Models.py

class GreenBased(models.Model):
    NumOfStudents = models.CharField(max_length=300,blank=True)
    Green = models.CharField(max_length=300,blank=True)
    class Meta:
        managed = False
        db_table = "GreenStats"

class YelloBased(models.Model):
    NumOfStudents = models.CharField(max_length=300,blank=True)
    Yellow = models.CharField(max_length=300,blank=True)
    class Meta:
        managed = False
        db_table = "YellowStats"

GreenStats and YellowStats tables contains only 2*2 rows in mysql Can someone please help me to identify this issue ?

HassenPy
  • 2,083
  • 1
  • 16
  • 31
user3128771
  • 27
  • 1
  • 1
  • 9
  • did you check this? http://stackoverflow.com/q/16790375/4724196 – HassenPy Jun 20 '15 at 12:03
  • I checked it already. In DJango 1.8, Json library has been changed, I'm missing something :(.. The line response_data['message'] = list(students) seems to be failing in the view. I'm trying to fix the issue, but couldn't solve yet – user3128771 Jun 20 '15 at 12:13
  • Sorry, this line is failing return HttpResponse(JsonResponse(response_data), content_type="application/json") – user3128771 Jun 20 '15 at 12:17
  • If you're going to exchange JSON and build some kind of api, may I suggest http://www.django-rest-framework.org/ ? It features tools to build json views, advanced customizable serializers, and automatic filtering. – spectras Jun 20 '15 at 12:48

1 Answers1

8

You have to serialize your student objects list, try something like this:

from django.http import HttpRequest,HttpResponse
from django.http import JsonResponse
from json import dumps
from django.core import serializers


def get_stats(request):
    if request.method == "POST":
        srch_dropV = request.POST['srch_dropAJ']
    else:
        srch_dropV = ''
    if(srch_dropV == 'Green'):
        students = GreenBased.objects.all()
    if(srch_dropV == 'Yellow'):
        students = YellowBased.objects.all()
    response_data = {}
    try:
        response_data['result'] = 'Success'
        response_data['message'] = serializers.serialize('json', students)
    except:
        response_data['result'] = 'Ouch!'
        response_data['message'] = 'Script has not ran correctly'
    return JsonResponse(response_data)

Notice the line change in :
response_data['message'] = serializers.serialize('json', students)

Also JsonResponse does the trick on its own, so no need to wrap it in a HttpResponse.

check the docs for more customization: https://docs.djangoproject.com/en/1.8/topics/serialization/

Hope this helps!

HassenPy
  • 2,083
  • 1
  • 16
  • 31