Plotting Graphs in Django using ChartJS

I am working on creating a graph using ChartJs to visualize my expenses.

Below is a snippet of my view:

@login_required
def index(request):
    truncate_month = connection.ops.date_trunc_sql('month', 'date_reg')
    expense = Expense.objects.extra({'month': truncate_month}).values('month').annotate(Sum('total_amount'))
    return render(request, 'home/index.html', {"expense": expense})

Within my template:

{{ expense }}

The data is displayed in the format shown below:

[{
   'month': '2015-12-01',
   'total_amount__sum': 900.0
}, {
   'month': '2016-01-01',
   'total_amount__sum': 19334.0
}] 

I would like to know how to format this data to be compatible with chartjs.

Example structure for ChartJs:

labels: ["January", "February", "March", "April", "May", "June", "July"], //Here represent the months
datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.2)",
        strokeColor: "rgba(220,220,220,1)",
        pointColor: "rgba(220,220,220,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: [65, 59, 80, 81, 56, 55, 40] //Here corresponds to 'total_amount__sum'
    },
    ...

Answer №1

Instead of bryanph's suggestion to use Values_list, you can also try using the Values function and then escape the quotes from ASCII in the template. This can be achieved by applying the safe filter.

Snippet in View: expenditures = expense.values('date', flat=True)

Template:

{{ expense|safe }}

Answer №3

To integrate underscore.js, one method is to utilize the following code:

return render(request, 'home/index.html', json.dumps({"expenses": expenses}))

Within the template:

data = JSON.parse({{ expenses|safe }});

var labels = _.pluck(data, 'month');
var amounts = _.pluck(data, 'total_amount__sum');

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

What is the best way to display a list of database records using Django?

Is there anyone who can assist me with this? I have a list of 60 records from a Django database in my HTML file. My goal is to display that list in a table with 6 columns and 10 rows. However, when using the {% for %} command in the HTML file, the list app ...

Is there a way to stop a setTimeout function in React before it is triggered?

In my application, I have set up a functionality where pressing a button starts the clock countdown. If no action is taken within 23 seconds (23000), the state changes to "this.state.user". This part is working correctly. However, if you click on the elem ...

Retrieving input values with JQuery

HTML <td data-title="Quantity"> <div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10"> <button class="btn-minus bg_tr d_block f_left" data-item-price="8000.0" data-direction= ...

Tips for positioning a div relative to another div while controlling its z-index

Hey there, take a look at the image below https://i.sstatic.net/zYiaY.png The issue I'm facing is quite common - I have div 1 and div 2 visible in a loop, but divs 3 are hidden. When div 2 is clicked on, everything is great so far. However, what I wa ...

The "flickering" effect of the div is like a dance, moving gracefully between fade outs and

I am encountering a similar issue as described in this thread: same problem (fiddle: original fiddle). However, I am still learning JavaScript and struggling to apply the solution provided because my HTML code is slightly different. Can someone please assi ...

Adding a class to a div upon loading: A guide

Currently using the following script: $(document).ready(function() { $(".accept").change(function () { if ($(this).val() == "0") { $(".generateBtn").addClass("disable"); } else { $(".generateBtn").remove("dis ...

When a React component mounts repeatedly, it can lead to complications within the useEffect hook

In our React application, we have implemented a custom hook to send data to Google Analytics. To avoid sending duplicate values, we included a unique "marker" string that captures the value of the data being sent. The hook generates a new "marker" each tim ...

MySQL field being updated upon page unload

I'm currently developing a Content Management System (CMS) that allows users to access and organize records within a MySQL database. One of the features I have implemented is a user login system for the CMS. As part of this project, I am working on in ...

Cross-origin resource sharing (CORS) policy issue arises when the 'Access-Control-Allow-Origin' header is not included in the requested resource, especially when utilizing an iframe in a React

I am trying to link a website to a button using an iframe. This website allows access to all domain names. Below is the code for my button: <Button component={NavLink} activeClassName={classes.activeBtn} to="/searchEngine&qu ...

Django - Recognizing the various types of IntegrityError situations

I have encountered an issue with the combination of django and MySQL where duplicate data is sometimes inserted into my database, resulting in django raising an IntegrityErrror. The problem lies in the fact that django/python uses the same error message f ...

What could be causing Highchart to return the error message "Typeerror: undefined variable byte"?

My current project involves creating a graph using highchart and updating values every second. I am also working on displaying data in Mb, Kb, and Gb format on the graph by developing a function to convert byte values. Here is a snippet of my code: // hi ...

Adding and removing form fields in a table dynamically using AngularJS

I need to dynamically add multiple form fields when a button is pressed, and I want all the fields to be displayed in a table format (each field should have its own space in a <td>field</td> structure). Currently, I am facing an issue where if ...

Unable to pass parameters using ViewBag in jQuery within a partial view

Currently, I am in the process of building an MVC3 application with razor syntax. My focus right now is on developing the partial class that will be responsible for handling comments. This is a snippet of my code: <script src="../../Scripts/jquery.js" ...

Fetching a JSON object from an external URL using JavaScript

Currently, I am working on a project using JavaScript and have an API that provides me with a JSON Object. You can access this JSON object by clicking on the following link: . Within this JSON object, there is a specific element located at JSONOBJECT.posi ...

Scripting in jQuery to create dropdown menus

I've encountered a unique issue on my website where a user's selection from one list should update the values in another list: <form id="form1"> <div> <select id="workField"> <option value ...

Slider handle for Material UI in React component reaches the range value

In my application, I am using a range slider component from material-UI. The main page displays a data table with the fields: id, name, current price, new price. The current price for each item is fixed, but the new price will be determined based on the s ...

Tips for Saving process.argv in a .js File for Future Reference

I am struggling with passing process.argv value to a config file for later use. I am trying to call it from npm scripts. I have the following config file: module.exports = { foo: proccess.argv[2] } So far, I have tried calling it via node config.js &apo ...

Using the Map Function in React JS to Dynamically Render Radio Buttons with Material-UI

Hey everyone, I'm looking for some assistance in replacing the old classic radio button with a new one using material-ui. I've been trying but haven't been successful so far. Any suggestions would be greatly appreciated. Thanks in advance. Y ...

Troubleshooting pagination issues with Django REST Framework on a cloud server

I successfully implemented pagination using the "PageNumber" Pagination feature in Django Rest framework on my local machine. However, when I deployed the same code on a remote server, it failed to return results with pagination. This is the Pagination Cl ...

Turning HTML into an image with the power of JavaScript

Utilizing html2canvas to convert a div into an image, everything is functioning properly except for the Google font effect. The image shows how it eliminates the effect from the text. https://i.stack.imgur.com/k0Ln9.png Here is the code that I am using f ...