Creating a pie chart using Highcharts in a Django framework

Trying to create a pie chart in Django with data from my "Results" model. The model has two fields:

+--------+------------+
| result |    date    | 
+--------+------------+
| passed | 2017-03-30 | 
| passed | 2017-02-30 | 
| passed | 2017-03-30 | 
| failed | 2017-03-30 |
| failed | 2017-03-29 |
| passed | 2017-03-29 | 
| passed | 2017-03-30 | 
-----------------------

The goal is to count the number of passed and failed values for a specific date, and represent this information in a pie chart.

For example, on 2017-03-30 there were 4 passes and 1 fail. https://i.sstatic.net/3sLxv.png

chart_test.html:

{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
</head>
<body>
    <script type="text/javascript">
        $(function () {
        $('#chart_container').highcharts({
        chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie'
    },
    title: {
        text: 'hello'
    },
    tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                style: {
                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                }
            }
        }
    },
    series: [{
        name: 'Brands',
        colorByPoint: true,
        data: [
          {% for cat in responses_pie %}
            [
            {{ cat.count }} 
            ],
            {% endfor %}
            ]
    }]
        });
        });
    </script>
    <div id="chart_container" style="height: 300px"></div>
</body>
{% endblock %}

views.py:

def chart_test(request): 
    responses_pie =  Results.objects.filter(date=date.today()).annotate(count=Count('result'))  
    return render(request,'mbr/chart_test.html',{'responses_pie': responses_pie})

Answer №1

If you're looking to enhance your charts, I recommend utilizing an external app that integrates with Highcharts. One great option is chartkick, which can be found at https://github.com/mher/chartkick.py. Simply provide a list of tuples to the view and let the app handle the chart rendering. For example:

browser_stats = [('Chrome', 52.9), ('Firefox', 27.7), ('Opera', 1.6),
                 ('Internet Explorer', 12.6), ('Safari', 4)]

In your template, include:

{% pie_chart browser_stats %}

You can see the result here:

Less work, best performance

:)

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

Implement functionality in Angular to perform tasks when the page is reloaded

I need to perform certain actions in Angular when the page is reloaded, such as adding items to local storage before the page loads and removing items after the page has fully loaded. In other words, I want to execute some tasks both before and after refr ...

The .ajaxSubmit function in jquery.form.js seems to be malfunctioning when using the data option

I'm currently working with the jQuery plugin jquery.form.js and I'm looking to programmatically submit a form while including a file. Although I've set up the code and options to work with $.ajax, it's not functioning with .ajaxSubmit. ...

What could be causing this JavaScript to output undefined?

const urls = [ "http://x.com", "http://y.com", "http://z.com", ]; for (let j=0; j<urls.length; j++) { setTimeout(function() { console.log(urls[j]); }, 3000); } I'm inserting this code snippe ...

What is the best way to prevent useEffect from triggering when a modal is being rendered?

I'm currently developing a react movie application. I am facing an issue with the hero picture feature that displays a random popular movie or show. Whenever I click the button to open a modal, the useEffect function is triggered and changes the movie ...

Adaptable material for collapsible panels

I'm facing a challenge with implementing an accordion menu. My goal is to have a 4 column layout that transforms into an accordion menu when the browser width is less than 600px. It almost works as intended, but there's a glitch. If you start at ...

Customize Bootstrap 5: Changing the default color scheme

Currently, I am utilizing Bootstrap 5 (v5.2.1) along with a form on my website. I am attempting to customize the default styles for form validation. Specifically, I want to modify the colored 'tick' or 'check' icon that is displayed wh ...

Issue with Bootstrap Navbar dropdown functionality not functioning correctly in browsers, but working fine on Codepen

I'm encountering an issue with a dropdown menu in the navbar of my document. The dropdown menu works fine in my codepen but not in my text editor (Sublime). I've tried various solutions and couldn't find a fix, so I'm reaching out here ...

Expanding Images in Bootstrap 4 Carousel

I am encountering some difficulties with a basic carousel implemented using Bootstrap 4. The carousel contains 3 images with the class d-block w-100, which is supposed to make the images stretch to the full width of the screen. However, in my case, the ima ...

Restrict Text Input Field to Accept Only Specific Domain

Hey there! I've set up a text input box for users to link their Tripadvisor page to their profile. I want to make sure that when they paste the URL in, it is checked for the correct format. For example, if someone pastes: or , then allow the link. Ho ...

Tips for encoding a base64 string into formats such as PDF, doc, xls, and png using jQuery, JavaScript, and HTML5

Need help handling base64 strings received from the server to save files in multiple browsers (IE, FF, Chrome). If receiving a PDF base64 string, how can it be saved in the browser? Also, if receiving an Image or Doc base64 string, what is the process fo ...

Struggling to figure out the ::before border trim issue

As I work on designing a banner for a webpage, I have added a sliced bottom right border using the ::before pseudo class. The code snippet I used includes: &::before { content: ""; position: absolute; bottom: 0; right: 0; ...

Troubleshooting Unresolved Issues with MongoDB and Node.js Promises

In my node.js code, I have utilized MongoDB to retrieve certain numbers. Below is the snippet of my code: MongoClient.connect('mongodb://localhost:27017/mongomart', function(err, db) { assert.equal(null, err); var numItems = db.col ...

What is the best way to assign dynamic values for array destruction?

Is there a way for me to avoid manually writing out six lines by implementing a loop to retrieve all six values from one line instead? console.log(array[0].name.LINE1) console.log(array[0].name.LINE2) console.log(array[0].name.LINE3) console.log(array[1].n ...

Tips for transferring state value from a form to a child modal

As a newcomer to React, I am uncertain about the best approach to take in my project. Specifically, I have a modal component that should appear once the user fills out a form and clicks on the Preview Voucher button to display the entered values. Below, yo ...

The charts created using chartjs-vue display no data

After following some examples to create a test chart, I am facing an issue where the chart renders blank with dummy data. https://i.sstatic.net/RD77S.png My initial suspicion is that maybe the options are not being passed for the lines, but it seems like ...

How to break out of an endless loop in Node.js and Express.Js

I have developed an Express app that is designed to paginate through an external API call. I have thoroughly examined the code but for some reason, the loop condition to break the function isn't being triggered. Any assistance on this matter would be ...

AngularJS personalized date selector directive

Looking to create a unique datepicker directive with a personalized template. Feeling lost on where to begin constructing it... Any suggestions on incorporating date data into my directive? Your guidance or tips on how to approach this project more effe ...

Ways to stop Bootstrap 4 dropdown from appearing when clicking on an input field?

Here is a straightforward bootstrap dropdown menu example, but with a twist - the toggle element is a text input. Instead of showing the dropdown on click event, I want it to appear when the user inputs something so I can dynamically populate the menu base ...

Is there a convenient feature in WebStorm for quickly inserting a lambda function in TypeScript that matches the current argument's signature while coding?

While working with promise chains in TypeScript, I often find myself dealing with a syntax tax that can become cumbersome. It would be great to have a way to automate this process, especially when using WebStorm. My ideal situation would involve having an ...

Disappearing Data: Struts2 Autocompleter's Entries Vanishing Upon Submit Button Click

I am currently utilizing the auto-complete feature from The issue I am facing is that when I type "Ball", the auto-complete suggests "Balloon". Even though both "Balloon" and "Balloon" appear in the text field and the list, when I click elsewhere on the s ...