Skip to content

Passing data to class-based django-jchart views #20

@joeDiHare

Description

@joeDiHare

Is there a way to pass custom data to the views instead of hard-coding it?
The examples in this repo have hardcoded data like:

from jchart import Chart
from jchart.config import Axes, DataSet, rgba


class TimeSeriesChart(Chart):
    chart_type = 'line'

...
    def get_datasets(self, *args, **kwargs):
        data = [{'y': 0, 'x': '2017-01-02T00:00:00'}, {'y': 1, 'x': '2017-01-03T00:00:00'}, {'y': 4, 'x': '2017-01-04T00:00:00'}, {'y': 9, 'x': '2017-01-05T00:00:00'}, ...
        return [{
            'label': "My Dataset",
            'data': kwargs['data']
        }]

But I can't seem to overwrite get_datasets() to accept data from other scripts, eg. this won't work and will load empty data:

#views.py
class MainView(ListView, FormMixin):
    template_name = "src/template.html"
    model = DataClass

    def get_context_data(self, **kwargs):
        context = super(SingleFileView, self).get_context_data(**kwargs)

        lc = LineChart()
        lc.get_datasets(data=[loc.latitude for loc in locations_dis])
        context['line_chart'] = lc#data=[loc.latitude for loc in locations_dis])

        return context

class LineChart(Chart):
    chart_type = 'line'

    def get_datasets(self, **kwargs):
        try:
            data = kwargs['data']
        except KeyError:
            data = []
        return [{
            'label': "My Dataset",
            'data': data
        }]

Similarly, adding a __ init() __ will mess things up.

What is the django-jchart way to pass data do a view?

This gets more confusing when trying to implement the async loading. As per the doc, we should add in the url.py:

from src.views import LineChart

urlpatterns = [
    url(r'^src/', include('src.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'^charts/line_chart/$', ChartView.from_chart(LineChart()), name='line_chart'),
]

but how to pass the data to LineChart()?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions