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 ?

4
  • did you check this? stackoverflow.com/q/16790375/4724196 Commented Jun 20, 2015 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 Commented Jun 20, 2015 at 12:13
  • Sorry, this line is failing return HttpResponse(JsonResponse(response_data), content_type="application/json") Commented Jun 20, 2015 at 12:17
  • If you're going to exchange JSON and build some kind of api, may I suggest django-rest-framework.org ? It features tools to build json views, advanced customizable serializers, and automatic filtering. Commented Jun 20, 2015 at 12:48

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.