使用Django,AJAX和JSON根据用户输入更新图表 [英] Using Django, AJAX and JSONs to update charts based on user input

查看:104
本文介绍了使用Django,AJAX和JSON根据用户输入更新图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Django,我想可视化我连接的SQLite数据库中的数据.我已经到了可以通过Django视图查询此数据并在d3图形中将其可视化的地步.现在,我希望允许用户使用下拉列表来自定义他们自己的查询,在这种情况下,允许他们选择一个与数据库中一列值相对应的数字.

Using Django I want to visualise data from my connected SQLite database. I have come to the point where I can query this data through Django views and visualise it in a d3 graph. Now I wish to allow a user to use a drop down list to customise their own queries, in this case allowing them to select a number which corresponds to a column of values in the database.

我使用JSON来创建下拉列表,并在Django视图中基于静态查询创建了此JSON.同样,我使用JSON来检索图的数据,这是我遇到的困难.

I used a JSON to create the drop down list, creating this JSON in a Django view based on a static query. Similarly I use a JSON to retrieve the data for the graph, this is where I have some difficulties.

尽管我将JSON返回到控制台,但我希望在d3.json()中使用它来显示值.我希望通过将json返回到URL并使用d3访问它来完成此操作.但是我遇到了以下错误:

Although I get a JSON returned to my console, I wish to use it in d3.json() to display the values. This I wish to do by returning the json to a url and access that with d3. However I run into the following error:

GET http://127.0.0.1:8000/database/db_getselection/1416/ 500 (INTERNAL SERVER ERROR)

模板

<div class="BoxIt">
    <!-- Make a list of all ReportDataDictionaryIndex values, based on database table -->
    <div class="div-dropdown" style="height:25px;">
        <!-- Drop down list directly from database -->
        <select id="selected_variable" name="selected_variable"></select>
        <div id="results_selection"></div>
    </div>

    <h2>sel_var is: {{ sel_var }}</h2>
    <h2>variable_data_Te: {{ variable_data_Te }}</h2>

    <div class="div">
        <!-- Chart to visualise data -->
        <svg id="variable_data_plot" width="400" height="300"></svg>
    </div>
</div>

JS/jQuery

<script>
    $.getJSON('{% url "db_dictionaryindices" %}', function(options) {
        var select = document.getElementById("selected_variable");
        for (var i = 0; i < options.length; i++) {
            var opt = options[i].reportdatadictionaryindex;
            var el = document.createElement("option");
            el.textContent = opt;
            el.value = opt;
            select.appendChild(el);
        };

        $("#selected_variable").change(function () {
            var url = "/database/db_getselection/" + $("#selected_variable").val() +"/";
            var selected_var = $("#selected_variable").val();
            console.log(url);
            console.log("Selected variable: "+selected_var);
            console.log("selection is working!") // sanity check
            $.ajax({
                url: url,
                type: "POST",
                dataType: 'json',
                data: { selected_variable : selected_var },

                success: function(data){
                    console.log(data);
                    var post_data = data;
                    drawLineChart(post_data);

                    console.log("success"); // another sanity check
                    //$("#results_selection").html("<strong>Success: "+data+"</strong>");

                },
                error: function(xhr,errmsg,err) {
                    console.log(data);
                    $('#results_selection').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                            " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
                    console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
                }
            });

            //Call this function within AJAX after the call returns a success
            function drawLineChart(post_data){

                    post_data.forEach(function (d) {
                        d.timeindex = +d.timeindex;
                        d.value = +d.value;


                        var vis = d3.select("#variable_data_plot"),
                                WIDTH = 400,
                                HEIGHT = 300,
                                MARGINS = {
                                    top: 20,
                                    right: 20,
                                    bottom: 20,
                                    left: 50
                                };

                        //d3.scale.linear uses two properties called range and domain to create the scale. Range defines the area avaiable to rende the graph, and Domain defines the min and max values.
                        var xScale = d3.scale.linear()
                                .range([MARGINS.left, WIDTH - MARGINS.right]).domain([0, d3.max(post_data, function (d) {
                                    return d.timeindex
                                })]);

                        var yScale = d3.scale.linear()
                                .range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0, 50]);

                        //Create axis using scales defined
                        var xAxis = d3.svg.axis()
                                .scale(xScale);
                        //.orient("bottom");

                        var yAxis = d3.svg.axis()
                                .scale(yScale)
                                .orient("left");

                        vis.append("svg:g")
                                .attr("class", "x axis")
                                .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
                                .call(xAxis);

                        vis.append("svg:g")
                                .attr("class", "y axis")
                                .attr("transform", "translate(" + (MARGINS.left) + ",0)")
                            //.attr("y", 6)
                            //.attr("dy", ".71em")
                            //.style("text-anchor", "end")
                                .call(yAxis);

                        var line = d3.svg.line()
                                .x(function (d) {
                                    return xScale(d.timeindex);
                                })
                                .y(function (d) {
                                    return yScale(d.value);
                                });

                        vis.append("svg:path")
                                .attr('d', line(post_data))
                                .attr('stroke', 'green')
                                .attr('stroke-width', 2)
                                .attr('fill', 'none')
                                .attr("class", "line");
                    });

            };
        });
    });

    // acquire csrf token using jQuery
    function getCookie(name) {} // ETC...


</script>

database/views.py

def db_data(request):
    return render(request, 'database/database.html')

def db_getselection(request, sel_var):
    sel_var = request.POST.get('selected_variable')

    logr.debug(sel_var)
    variable_data_Te = Reportdata.objects.using('visdata').filter(reportdatadictionaryindex=sel_var).values("timeindex", "value")[:100]
    variable_data_Te = json.dumps(list(variable_data_Te), cls = DjangoJSONEncoder)

    return HttpResponse(variable_data_Te, content_type = 'application/json')

def db_dictionaryindices(request):
    DataDictionaryIndices = Reportdatadictionary.objects.using('visdata').values("reportdatadictionaryindex")[:15]
    DataDictionaryIndices = json.dumps(list(DataDictionaryIndices), cls = DjangoJSONEncoder)
    return HttpResponse(DataDictionaryIndices, content_type = 'application/json')

database/urls.py

urlpatterns = patterns('',
    url(r'^$', views.db_data, name='db_data'),
    url(r'^db_getselection/(?P<sel_var>\d+)/$', views.db_getselection, name='db_getselection'),
    url(r'^api/db_dictionaryindices/$', views.db_dictionaryindices, name='db_dictionaryindices'),
    ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

这是我之前通过设置静态值进入图表的一些数据的图像.

Here an image of some data I got into the graph previously by setting a static value.

推荐答案

一个月后,我知道了这一点,并将回答我自己的问题.将问题编辑为工作脚本.

Month later, I figured it out and will answer my own question. Edited the question to be the working script.

代替尝试使用d3.json和访问URL,我可以选择直接在AJAX成功中调用d3图的功能:

Instead of trying to use d3.json and accessing a URL I could alternatively use call the function of the d3 graph directly within my AJAX success:

$.ajax({
    url: url,
    type: "POST",
    dataType: 'json',
    data: { selected_variable : selected_var },

    success: function(data){
        console.log(data);
        var post_data = data;
        drawLineChart(post_data);
    })}

然后,我不再使用原本想使用的d3.json,而是直接使用数据来创建图形:

Then instead of using d3.json as I orginally wanted to use, I use the data directly to create the graph:

function drawLineChart(post_data){

    post_data.forEach(function (d) {
        d.timeindex = +d.timeindex;
        d.value = +d.value;

    //ETC
    )}
}

结果

如果有人发现任何可能更有效或更有效的方法,请告诉我.

If anyone sees anything that could be more efficient or better, please let me know.

这篇关于使用Django,AJAX和JSON根据用户输入更新图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆