[Answer]-Pulling Data from Django database

1👍

The easiest way for doing that is querying Django through Ajax. You must define a view that return some data (preferably json) and then call it from your js script.

from django.core import serializers
from django.http import HttpResponse

def all_questions(request):
    """
    Most of the time you will have to do some extra work formating the json in 
    order to match the format  that the JS library is expecting.

    I can see your graph is expecting something like:

        series: [{  
                name: <some_sustom_name>
                data: <array of values>
            }
        ], 


    So you need to provide to the JS library the data it is expecting. 
    That means some array (or perhaps similar data structure). 

    """

    questions = Questions.objects.all()
    response = serializers.serialize('json', questions)

    # Now response contain a representation of a 
    # json object that has a property called data
    # besides, that property contain a list of Django objects.
    response = "{data: %s}" % response    

    return HttpResponse(response, content_type="application/json")

For more info about the content of response see: Serializing Django Objects

Now, lets assume you got the data in your javascript (the Ajax call was successfull) you will have something like:

{data: [list of serialized Django objects]}

You just have to process list above and extract the data for your graph. Of course you can obtain that list directly from the Django view . That’s your call.

See this Kendo demo for more info on what to put in series section of graphs.

Querying Django through Ajax from JQuery.

For this you need code like this:

$.ajax({
    type: "GET",                    // 1
    url:"url_to/you_view",          // 2
    data: {                         // 3
        'zip': zip,             
    },
    success: function(data){        // 4    

    },
    error: function(error){         // 5
        alert("Error");
    }
});

1 – Specification of the request method (GET, POST, UPDATE, etc ….)

2 – The url pointing to your view.
Note that there are any protocol specification (http). As your js lives in your django app
the url is relative to this app. For this you need some url like:

urlpatterns = patterns('your_app.views', 
    ...
    url(r'url_to/you_view', 'your_view')
    ...
)

3 – Optional, some data to send to de django view. (in your case you don’t need it)

4 – This is important, here you will process the data returned by the server when the request success.
Following the example above data here is a json object like:

{data: [...]}

where [...] stands for a list of django serialized objects with jason format.(See the links for documentation).

5 – On error this function will be called instead of that specified by success.

For more info on $.ajax object from JQuery see the $.ajax API Reference.

Leave a comment