peopledoc / django-chartjs

Django Class Based Views to generate Ajax charts js parameters.
Other
404 stars 112 forks source link

BaseLineOptionsChartView: Need an option `callback` for y-axes ticks to line chart #50

Closed gauravndabhade closed 4 years ago

gauravndabhade commented 4 years ago

I am trying to configure line chart options, for formatting y-axes tick values.

class LineChartJSONView(BaseLineOptionsChartView):

    ...
    ## I have implemented `get_labels` & `get_data` functions
    ...

    def get_options(self):
        return {
            "responsive": True,
            "scales": {
                "xAxes": [{
                    "scaleLabel": {
                        "display": True,
                        "labelString": "Daily"
                    }
                }],
                "yAxes": [{
                    "scaleLabel": {
                        "display": True,
                        "labelString": 'Count'
                    },
                    "ticks": {
                        "beginAtZero": True,

                         ## Need to pass function from `dict`
                        "callback": function (value) { if (value % 1 === 0) { return value; } }
                    }
                }],
            },
        }

line_chart_json = LineChartJSONView.as_view()

I have called line_chart_json in template.

...
<html>
    <canvas id="myChart" width="500" height="400"></canvas>
    ...
<script type="text/javascript">
    $.get('{% url "line_chart_json" %}', function (response) {
        var ctx = $("#myChart").get(0).getContext("2d");
        new Chart(ctx, {
            type: 'line',
            data: response.data,
            options: response.options
        });
    });

</script>
</html>
Natim commented 4 years ago

I don't think we should support writting JavaScript in a Python string and then evaluate it in JS.

I guess one should define the javascript callback in javascript and then add it like that:

    $.get('{% url "line_chart_json" %}', function (response) {
        var ctx = $("#myChart").get(0).getContext("2d");
        var options = response.options;
        options.scales.yAxes[0].ticks.callback = function (value) { if (value % 1 === 0) { return value; } };
        new Chart(ctx, {
            type: 'line',
            data: response.data,
            options: options
        });
    });