Chartjs-How to put arguments in a jchart.Chart class

0👍

Yep.

You have two possibilites:

  • the hard way: you make an AJAX call that returns an array, and you populate this in JavaScript. This implies to make a JSON view that returns a JSON array
  • the easy way: you need to use class-based-view‘s to make modern application and in your class you override the method get_context_data()

like this:

class GeneralStudyResultsView(generic.TemplateView):

    template_name='general_study_results.html'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(GeneralStudyResultsView, self).get_context_data(**kwargs)
        # Create a variable you fill
        context['my_big_sql'] = GeneralStudyModel.objects.all()
        return context

And from there, in your template file (this is your template file, not a JavaScript file) general_study_results.html add something like:

<script>
var myData = 
{% for row in my_big_sql %} 
    {{ row.column }}{% if not forloop.last %},{% endif %}
{% endfor %};
</script>

And then you have all your data in your HTML file ready to be show thanks to charts.js

0👍

Just add a suitable initialiser to the chart class as follows:

class HomeTotalStudies(Chart):

    def __init__(self, hosp, *args, **kwargs):
        self.hosp = hosp
        super().__init__(*args, **kwargs)

    def get_datasets(self,**kwargs):
        modality = ['CT','MG','RF','DX']
        count = []
        if self.hosp=='somestring' #this is the variable i want to get from the views.py
            studies = GeneralStudyModel.objects.all()
        else:
            studies = GeneralStudyModel.objects.filter(equipmentattributes__institution_name__exact=self.hosp)
    ...

then in your view:

from charts.chartsclass import HomeTotalStudies

def home(request):

    hosp = request.user.userprofile.hospital
    chart = HomeTotalStudies(hosp='whatever')
    return render .....

Leave a comment