Utilizing Django Data for Dynamic Google Charts

Observation:

def view_page(request,
    template = 'home.html'):
    if request.user.is_authenticated():
        data = [['jan'],[12],[-12]]

    context = {
        'data' : data,
    }
    return render(
        request, template, context)

Design:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawVisualization);

function drawVisualization() {


  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Month');
  data.addColumn('number');
  data.addColumn('number');

  data.addRows({{ data|safe }});

  // Create and draw the visualization.
  new google.visualization.ColumnChart(document.getElementById('visualization')).
      draw(data,
           {title: "blabla",
            width:600, height:400,
            bar: { groupWidth: '90%' },
            isStacked:"true",
            legend:"none" }
      );

}
</script>

I am attempting to pass the array values to the chart rows, but facing difficulties. The chart is not being rendered even though other functionalities are working properly.

The main objective is to extract model fields into an array and utilize it for chart representation. If I cannot achieve this, progress will be hindered.

Upon displaying {{ data }} in the template, the following result is obtained:

[[0], [12], [-12]]

Could this be the incorrect format? How can I modify it for Google Charts to comprehend it as row values?

Any form of guidance or assistance would be highly appreciated.

Thank you in advance

Answer №1

After analyzing the data table definition in the code, it appears that there are three columns specified...

var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number');
data.addColumn('number');

However, based on the question, it seems that only two columns are required...

var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number');

To add a single row of values, the format should be...

['Month', 0]

For adding all the rows using addRows, the format should be...

[
  ['Month', 0],
  ['Month', 12],
  ['Month', -12]
]

Within your views context, ensure to change 'data' : data to 'data': json.dumps(data)

Remember, it is essential to use JSON either in JavaScript or in the view context.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There seems to be an issue with the React 15 setState function not working on

My react setState after action isn't functioning properly. handleChange = () => { this.setState({foo: 'bar'}); < - it's working console.log('hellow') < - not working, console is clean } I have double-check ...

Incorporating the values of JavaScript objects into a global variable

I'm currently developing a bank account program and facing a challenge in adding my direct debits (DDs) into the global variable. When I create new objects using my constructor function and add them into the bank account, only the last created DD is s ...

Incorporating JavaScript into a Rails Application

When I click on a link "link_to" in my rails app, I am attempting to trigger a JS file. To confirm that the asset pipeline is functioning correctly, I conducted a test with: $(document).ready(function() { alert("test"); }); The alert successfully po ...

The Angular Date Pipe is currently unable to display solely the Month and Year; it instead presents the complete date, including day, month,

I'm currently using the Bootstrap input date feature to save a new Date from a dialog box. However, I only want to display the month and year when showing the date. Even though I added a pipe to show just the month and year, it still displays the mont ...

Flask Session Persistence Issue: Postman Successful, Javascript Fails

Developing a Flask server to facilitate communication between backend Python functionality and Javascript clients on the web has been my recent project. I am trying to harness Flask's `session` variable to retain user-specific data throughout their in ...

What is the method for showcasing a single Observable from an Array of Observables in Angular?

I am facing a challenge with displaying questions from an Observable-Array one by one. Currently, I can only display all the questions at once using *ngFor in my HTML. Here is my component code snippet: import { Component, OnInit } from '@angula ...

Creating an array dynamically in response to an AJAX call

Is there a way to dynamically create an array after receiving an AJAX response? Upon getting the AJAX response, the variable data.villages contains the data. To iterate over its values, the jQuery each function can be used: $.each(data.villages, functio ...

What is the procedure for placing an item into a vacant area in react-dnd?

Looking to create a drag and drop list using react-dnd. Manage to put together an example: visit codesandbox example here Currently facing one issue: Unable to drop an item into an empty section. If trying to move image1 to the first or third group, un ...

require an array that contains an embedded object

When making a post request, I need to include an array with an object inside. I have observed that adding new properties inside an object works fine. However, when attempting to add properties while the object is inside an array, it does ...

Encountered an error in Discord.js: Undefined properties unable to be read (execute)

Here is the code snippet from my main file: const { Client, IntentsBitField, Collection, intents, SlashCommandBuilder } = require('discord.js') const { TOKEN, PREFIX } = require('./config.json') const fs = require('fs'); const ...

Leverage Reveal.js within Next.js by installing it as an npm package

I am currently working on a project that requires integrating Reveal.js with Next.js. However, I am having trouble displaying the slides properly. Every time I try to display them, nothing shows up. Even after attempting to display some slides, I still en ...

execute the command only if all ava tests succeed

I'm working on creating an npm script that will execute Ava, and if it is successful, will then run another deploy command. Is there a way to obtain the result of an Ava test in JavaScript, or to save it to a file or pass it to a subsequent command? ...

Trying to assign a property to an undefined variable inside a function

At the moment, I am configuring error messages on a login page for an extension using vue, and encountering issues within the importCreds() function. data(){ return { url:'', apikey:'', error:'', } }, meth ...

Vue3 CheckBox Component: A versatile option for interactive user interfaces

Struggling with incorporating checkboxes into a separate component. I have a child component with a basic card template and checkbox - essentially, a product list where each card should have a checkbox for deletion. Currently, as I loop through an array to ...

Creating connections between variables and elements in nested ngRepeats in Angular

I've been facing a challenge with my app where I need to update the comments section whenever a comment is added, edited, or deleted without having to refresh the page. I am using ngResource to handle queries for both articles and comments (e.g. $scop ...

Troubleshooting problem with image loading in AngularJS using ng-repeat

Recently delving into using AngularJS in my projects has presented a rather significant issue when utilizing ngRepeat to load thumbnails from a dynamic array into a DIV. While I won't dive deep into the entire application's details here, let me ...

Exploring Node.js and JSON: Retrieving specific object attributes

Utilizing ExpressJS, NodeJS, and Bookshelf.js In an attempt to display a user's list of friends, encountering the error "Unhandled rejection TypeError: Cannot read property 'friends' of undefined" when trying to access a property of the obj ...

Sorting `divs` based on the number of user clicks in JavaScript: A simple guide

I've implemented a script that tracks the number of clicks on each link and arranges them based on this count... Currently, everything is functioning correctly except when the <a> tags are nested inside a div. In such cases, the script ignores ...

The authentication0 router fails to initiate navigation

I'm currently using Auth0 in combination with Angular 2. The issue I am encountering is that my login code isn't redirecting to the home page after authentication. Based on my understanding, Auth0 does not handle the redirection process itself. ...

Converting an object to JSON in javascript: A step-by-step guide

I have been attempting to convert my object person into a JSON format. const person = new Object(); person.firstName = 'testFirstName'; person.lastName = 'testLastName'; var myJson = JSON.stringify(person); ...