Package: django-jchart-django3-uvm
django-jchartThis Django app enables you to configure and renderChart.JScharts directly from your Django codebase. Charts can than either be rendered directly into your Django template or served asynchronously to the webbrowser.Authors: Matthisk HeimensenLicence: BSDCompatibility: Django 1.5+, python2.7 up to python3.5Project URL:https://github.com/matthisk/django-jchartGetting Startedinstalldjango-jchartpip install django-jchartAdddjango-jchartto your installed apps.INSTALLED_APPS = (
    '...',
    'jchart',
)Enable template loading from app folders by adding the following property to yourTEMPLATESdjango configuration:TEMPLATES=[{'BACKEND':'django.template.backends.django.DjangoTemplates','APP_DIRS':True,# ...}]Frontend DependenciesFor the charts to be rendered inside the browser you will
need to include the Chart.JS library. Add the following
HTML before your closing</body>tag:<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"></script>If you want to make use ofasynchronous loading chartsyou will also need to include jQuery:<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>The Chart ClassAt the heart of this charting library lies theChartclass. This class describes a chart and defines which data it should display. The chart's 'class fields' map toChart.JS optionswhich describe how the chart should render and behave. By overriding theget_datasetsmethod on yourChartinstance you can define which data should be displayed.To define which type of chart you want to render (e.g. a line or bar chart), your chart class should set its class fieldchart_typeto one of "line", "bar", "radar", "polarArea", "pie", or "bubble". A chart class without this field is invalid and initialization will result in anImproperlyConfiguredexception.fromjchartimportChartclassLineChart(Chart):chart_type='line'get_datasetsTheget_datasetsmethod should return a list of datasets this chart should display. Where a dataset is a dictionary with key/value configuration pairs (see the Chart.JSdocumentation).fromjchartimportChartclassLineChart(Chart):chart_type='line'defget_datasets(self,**kwargs):return[{'label':"My Dataset",'data':[69,30,45,60,55]}]get_labelsThis method allows you to set the Chart.JSdata.labelsparameter. Which allows you to configurecategorical axes. For an example on how to use this feature see thispie chart.fromjchartimportChartclassPieChart(Chart):chart_type='pie'defget_labels(self,**kwargs):return['Red','Blue']Configuring ChartsA chart can be configured through the following class fields:scaleslayouttitlelegendtooltipshoveranimationelementsresponsiveAll of these fields map to the same key in the Chart.JS'options' object. For instance, if you wanted to create a chart that does not render responsively you would set the responsive class field to false:fromjchartimportChartclassUnresponsiveLineChart(Chart):chart_type='line'responsive=False# ...Most of these class fields require either a list of dicitonaries or a dictionary. With the exception ofresponsivewhich should be a boolean value. Be sure to read the Chart.JSdocumentationon how to use these configuration options.For your convenience there are some methods located injchart.configwhich can be used to produce correct dictionaries to configure Chart.JS properties. Most of these methods only serve as a validation step for your input configuration but some can also transform their input. Let's take a look at an example, how would you configure the X-Axis so it is not to be displayed:fromjchartimportChartfromjchart.configimportAxesclassLineChart(Chart):chart_type='line'scales={'xAxes':[Axes(display=False)],}jchart.configalso contains a method to create dataset configuration dictionaries. One of the advantages of using this method is that it includes a special propertycolorwhich can be used to automatically set the values for: 'backgroundColor', 'pointBackgroundColor', 'borderColor', 'pointBorderColor', and 'pointStrokeColor'.fromjchartimportChartfromjchart.configimportAxesclassLineChart(Chart):chart_type='line'defget_datasets(self,**kwargs):return[DataSet(color=(255,255,255),data=[])]Thejchart.configmodule contains methods for the properties listed below. Keep in mind that you are in no way obligated to use these methods, you could also supply Python dictionaries in the place of these method calls.<h5>Available configuration methods:</h5>
<code>Axes</code>, <code>ScaleLabel</code>, <code>Tick</code>, <code>DataSet</code>, <code>Tooltips</code>, <code>Legend</code>, <code>LegendLabel</code>, <code>Title</code>, <code>Hover</code>, <code>InteractionModes</code>, <code>Animation</code>, <code>Element</code>, <code>ElementArc</code>, <code>ElementLine</code>, <code>ElementPoint</code>, <code>ElementRectangle</code>Custom configuration optionsThere is another special class field namedoptionsthis has to be set to a dictionary and can be used to set any other Chart.JS configuration values that are not configurable through a predefined class field (e.g.maintainAspectRatio). The class fields have precedence over any configuration applied through theoptionsdictionary.fromjchartimportChartclassOptionsChart(Chart):chart_type='line'options={'maintainAspectRatio':True}# ...</pre></code><h4class="section-title"id="docs-rendering-charts"><aclass="fragment-link"href="#docs-rendering-charts">RenderingCharts</a></h4><p>ChartinstancescanbepassedtoyourDjangotemplatecontext.Insidethetemplateyoucaninvokethemethod`as_html`onthechartinstancetorenderthechart.</p><pre><codeclass="language-python"># LineChart is a class inheriting from jchart.Chartdefsome_view(request):render(request,'template.html',{'line_chart':LineChart(),})The following code is an example of how to render this line chart
    inside your html template:{{line_chart.as_html}}Asynchronous ChartsWhen rendering the chart directly into your HTML template, all the data needed for the chart is transmitted on the page's HTTP request. It is also possible to load the chart (and its required data) asynchronous.To do this we need to setup a url endpoint from which to load the chart's data. There is a classmethod available onjchart.views.ChartViewto automatically create a view which exposes the chart's configuration data as JSON on a HTTP get request:fromjchart.viewsimportChartView# LineChart is a class inheriting from jchart.Chartline_chart=LineChart()urlpatterns=[url(r'^charts/line_chart/$',ChartView.from_chart(line_chart),name='line_chart'),]You can use a custom templatetag inside your Django template to load this chart asynchronously. The custom tag behaves like the Django url templatetag and any positional or keyword arguments supplied to it are used to resolve the url for the given url name. In this example the url does not require any url parameters
    to be resolved:{%loadjchart%}{%render_chart'line_chart'%}This tag will be expanded into the following JS/HTML code:<canvasclass="chart"id="unique-chart-id"></canvas><scripttype="text/javascript">window.addEventListener("DOMContentLoaded",function(){$.get('/charts/line_chart/',function(configuration){varctx=document.getElementById("unique-chart-id").getContext("2d");newChart(ctx,configuration);});});</script>Chart ParameterizationIt can often be useful to reuse the same chart for different datasets. This can either be done by subclassing an existing chart class and overriding itsget_datasetsmethod. But there is another way to do this. Any arguments given to theas_htmlmethod are supplied to yourget_datasetsmethod. This makes it possible to parameterize the output ofget_datasetsLet's have a look at an example. Imagine we have price point data stored in a model calledPriceand this model has a field calledcurrency_type. We could render the chart for different currency types by accepting the value for this field as a parameter toget_datasets.fromjchartimportChartfromcore.modelsimportPriceclassPriceChart(Chart):chart_type='line'defget_datasets(self,currency_type):prices=Price.objects.filter(currency_type=currency_type)data=[{'x':price.date,'y':price.point}forpriceinprices]return[DataSet(data=data)]If we supply an instance of this chart to the context of our template, we could use this to render two different charts. This is done by using therender_charttemplate tag to supply additional parameters to theget_datasetsmethod:{%render_chartprice_chart'euro'%}{%render_chartprice_chart'dollar'%}For asynchronous charts any url parameters are passed to theget_datasetsmethod.fromjchart.viewsimportChartViewfrom.chartsimportPriceChartprice_chart=PriceChart()urlpatterns=[url(r'^currency_chart/(?P<>\w+)/$',ChartView.from_chart(price_chart))]To render this chart asynchronously we have to supply the url parameter as a second argument to therender_charttemplate tag, like so:{%loadjchart%}{%render_chart'price_chart''euro'%}{%render_chart'price_chart''dollar'%}ToDOComposable datasources (instead of having to rely on inheritance)Compare django-jchart to other Django chartig libraries (in the readme)ContributingReleasingTo release update the version of the package insetup.py.Add release toCHANGELOG.md.Run commands:python setup.py sdist bdist_wheel --universal
twine upload dist/*Add git tag to commit