chart.js ajax,GitHub – peopledoc/django-chartjs: Django Class Based Views to generate Ajax charts js…

  • Post author:
  • Post category:其他


Django Chartjs

Django Chartjs lets you manage charts in your Django application.

68747470733a2f2f7472617669732d63692e6f72672f70656f706c65646f632f646a616e676f2d63686172746a732e7376673f6272616e63683d6d6173746572

303e03c3469c1f418a13419573e09a65.png

68747470733a2f2f696d672e736869656c64732e696f2f707970692f762f646a616e676f2d63686172746a732e737667

This is compatible with Chart.js and Highcharts JS libraries.

Using a set of predefined Class Based Views you are able to get

started after writing just your SQL query.

Authors: Rémy Hubscher and contributors

Licence: BSD

Compatibility: Django 1.10, 2.2 and 3.0, python3.6 up to python3.8

Getting Started

Install django-chartjs:

pip install django-chartjs

Add it to your INSTALLED_APPS settings:

INSTALLED_APPS = (

‘…’,

‘chartjs’,

)

Using it

A simple Line Chart example.

1. Create the HTML file

{% load static %}

django-chartjs line chart demo

Some Line Charts loaded in Ajax!

$.get(‘{% url “line_chart_json” %}’, function(data) {

var ctx = $(“#myChart”).get(0).getContext(“2d”);

new Chart(ctx, {

type: ‘line’, data: data

});

});

2. Create the view with labels and data definition

from django.views.generic import TemplateView

from chartjs.views.lines import BaseLineChartView

class LineChartJSONView(BaseLineChartView):

def get_labels(self):

“””Return 7 labels for the x-axis.”””

return [“January”, “February”, “March”, “April”, “May”, “June”, “July”]

def get_providers(self):

“””Return names of datasets.”””

return [“Central”, “Eastside”, “Westside”]

def get_data(self):

“””Return 3 datasets to plot.”””

return [[75, 44, 92, 11, 44, 95, 35],

[41, 92, 18, 3, 73, 87, 92],

[87, 21, 94, 3, 90, 13, 65]]

line_chart = TemplateView.as_view(template_name=’line_chart.html’)

line_chart_json = LineChartJSONView.as_view()

3. Update urls.py with the new urls for TemplateView and AJAX call ‘line_chart_json’ as in chart.html

from .views import line_chart, line_chart_json

urlpatterns = [

‘…’,

path(‘chart’, line_chart, name=’line_chart’),

path(‘chartJSON’, line_chart_json, name=’line_chart_json’),

]

4. Get a Chart.js Line Chart

56f40700aa8b1ea4e71c74da65d94c79.png

It is that simple!

For other examples including a HighCharts line chart, don’t hesitate to look at the demo project.

Also, feel free to contribute your demo!