Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning JSON object from Django view to client via AJAX

Tags:

json

ajax

django

Basically, I am trying to turn raw SQL query result to JSON object and then send it to client-side via AJAX. Here is my view (I am using Django 1.8.6)

import MySQLdb
from django.db import connection
import json
from django.http import HttpResponse
from django.core import serializers
def test_view(request):
      cursor = connection.cursor()
      cursor.execute("select id, name from okved")
      data = cursor.fetchall
      json_data = serializers.serialize('json', data)
      return HttpResponse(json_data, content_type="application/json")

The respective URLConf

url(r'^test/$', test_view),

JQuery function

var test = function()
{
    $.ajax({
        type:"GET",
        url:"/test",
        dataType : 'json',
        cache: "false",
        data:{},
        success:function(response)
        {
            alert("Test successful");
        }
    });
    return true;
}

I am constantly getting GET http://127.0.0.1:8000/test/ 500 (INTERNAL SERVER ERROR) error, wheareas I follow all the recommendations that I have come across the previous threads here. I would really appreciate any help on this. I have blown my mind trying surfing Stackoverflow on this.

like image 928
Edgar Navasardyan Avatar asked Nov 03 '25 12:11

Edgar Navasardyan


1 Answers

First of all, 500 error is just an error code, django would give you stacktrace of where the error happens in the function stack, you should learn to read that and find where the error happens.

From you code sounds like you are trying to use serializers to serialize a raw query result. This wouldn't work because the raw result is a tuple of tuples, each sub tuple is a record returned from your database. Django serializers is only good at serializing objects queried from ORM. You'd better go with json.dumps() method. Here's last few lines in your views.py:

data = cursor.fetchall()
json_data = json.dumps(data)
return HttpResponse(json_data, content_type="application/json")

Here's the doc for django serializer.

like image 124
Shang Wang Avatar answered Nov 06 '25 04:11

Shang Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!