Error in parsing string data in Django Chart.js ajax using javascript

I'm currently working on creating a chart web page using Django and Chart.js within the views.py file of the Django framework.

class ChartView(TemplateView):
    template_name = 'graph.html'

    def get_context_data(self, **kwargs):
        context = super(ChartView, self).get_context_data(**kwargs)
        context['labels'] = ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
        context['datas'] = [12, 19, 3, 5, 2, 3]
        return context

When it comes to the html file (template file)

<script>
$( document ).ready(function() {
var data = {
    labels: {{ labels }},
    datasets: [
        {
            label: "Site Registrations in the Last 30 Days",
            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: {{ datas }}
        }
    ]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data);
});
</script>

An error is occurring during the rendering of the html page. The page source displays this:

<script>
$( document ).ready(function() {
var data = {
    labels: [u&#39;Red&#39;, u&#39;Blue&#39;, u&#39;Yellow&#39;, u&#39;Green&#39;, u&#39;Purple&#39;, u&#39;Orange&#39;],
    datasets: [
        {
            label: "Site Registrations in the Last 30 Days",
            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: [12, 19, 3, 5, 2, 3]
        }
    ]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data);
});
</script>

The issue lies with the data values being correctly displayed as {{ datas }}, while the labels receive incorrect values as {{ labels }}. I'm unsure of how to properly parse the string in Ajax/JavaScript. Any guidance on resolving this issue would be greatly appreciated. Thank you.

Answer №1

Instead of attempting to display the entire labels list directly as a Javascript array, consider constructing a Javascript array from the list:

var data = {
    labels: [{% for label in labels %}"{{ label }}", {% endfor %}],
...

Answer №2

To prevent HTML escaping, you must utilize the safe template filter.

The safe filter denotes that a string does not need additional HTML escaping before being displayed.

For instance:

{{ content|safe }}

Answer №3

Appreciate your recommendation. Recently made the switch from

   using python 2.7 to python 3.7

And everything is running smoothly.

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

Learn how to make a mesh in Three Js React refract its environment while keeping the background hidden from the camera

I've been grappling with this challenge for quite some time now, so any assistance would be highly valued! My aim is to create the illusion of an image being confined within a mesh structure. My initial idea was to utilize a mesh with defined thickne ...

Implementing pagination with Django-REST and AngularJS

I successfully integrated my angularjs app with django-rest, but encountered a problem when implementing pagination. Below is the code for my restservice and controller: // restservices.js // API call for all images in an event services.factory('Imag ...

Displaying JavaScript - Nothing to Echo in PHP

Using PHP to echo a JavaScript block, I have encountered an error message. echo "<script language='javascript' type='text/javascript'> jQuery(document).ready(function($){ var $lg = $('#mydiv'); ...

Employing ng-show and other related features within directive "A"

After browsing through similar inquiries, I am still unable to comprehend the solution. If I have a directive available at this link: http://pastebin.com/QtAzGv62 and now need to incorporate the functionality of "ng-show" (or any other standard angular di ...

Having trouble sending messages on the server?

Programmer Seeking Help with Adding Data on the Server using JavaScript Stack I am encountering an issue with my javascript code as I am attempting to use the post method to add data on the server-side, but it seems to not be posting successfully. Can ...

Unable to display the string following a space in the value attribute of an hbs file

<input type="text" class="form-control" id="exampleInputEmail2" name="productName" value={{product.productName}} > When I input 'Smart Phones' into product.produc ...

Getting the value of "Page=?" from the href attribute in an HTML tag can be done using Selenium Webdriver and Java

I am looking to extract the value "page = ?" from a specific "href" tag in the HTML code below. I need this value for my Selenium WebDriver script so that my loop can iterate up to page 53. Can someone guide me on how to retrieve the "page =" value mentio ...

Arranging an array of objects in Javascript based on the first attribute, and in cases of equality, sorting with another attribute

I have an array structured like this: let myarr = [{id:1 , name: "mark" , birthday: "1990-08-18"}, {id:2 , name: "fred" , birthday: "1990-08-17"}, {id:3 , name: "franck" , birthday: "1990-08-16"}, ...

What could be the reason for the variable not resetting in my event handler?

Check out the code I've written below: $(document).ready(function () { var default_var = 2; var show_var = default_var; var total_var = 8; var increment_var = 2; var start_var = show_var+1; var end_var = show_var+increment_v ...

What is the best method to reset values in ngx-bootstrap date picker?

At the moment, it is only accepting the most recently selected values. To see a live demo, click here. ...

Dynamic sliding box jumps instead of simply fading in/out

My app features both a navigation bar and a sub-navigation bar. Within the sub-navigation bar, users can click on a button that triggers the appearance of another sub-bar while hiding the original one. The new sub-bar should smoothly slide out from behind ...

Why does the result of parsing in Python through Ajax PHP differ from what is displayed on the screen?

Attempting to extract search results from a specific page proved to be challenging. After selecting the date range of 20-Nov to 22-Nov and filtering by the "財經" news category on the website, only 47 results were visible. However, running python php cod ...

The identical animation is experiencing delays in various directions

Having an issue with my image slider - when clicking on the previous image button, the animation takes longer compared to when clicking on the next image button, even though the animation duration is set to be the same for both. Any idea why this might be ...

Krajee Bootstrap File Input, receiving AJAX success notification

I am currently utilizing the Krajee Bootstrap File Input plugin to facilitate an upload through an AJAX call. For more information on the AJAX section of the Krajee plugin, please visit: Krajee plugin AJAX The JavaScript and PHP (CodeIgniter) code snippe ...

IE9 users are redirected to an ajax action when using Fancybox

I am currently experiencing an issue with using Fancybox in Magento admin, where everything works fine except for Internet Explorer 9. When I try to feed my fancybox by ajax, the link looks like this: <a class="fancybox fancybox.ajax" href="http://10.1 ...

What is the reason for not encountering an error when reading an array beyond its index limit?

Recently, while working on a pre-existing website with JavaScript code, I made an interesting discovery. I noticed that the code was accessing array items in a unique way: var value = myArray[0, 1]; This seems to be retrieving the second item of the arr ...

Vue API and Frame

Just starting out. Looking to display a skeleton while waiting for data from the API. Any ideas on how to achieve this? Appreciate any help My workaround involved implementing a timeout function ...

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...

retrieve a subdocument from an array in MongoDB

In my MongoDB database, I have the following data structure: {doc: { array_doc:[....//many documents]} } Currently, I am working with Mongoskin in MongoDB 2.2 with Node.js 0.8. var code_doc='HSKD41814541211'; var db = mongo.db(perm+"@127.0 ...

`What is the process for accessing page-specific data on Google Analytics using the analyticsreporting tool?`

I'm currently working on extracting specific analytics data using Google's analyticsreporting API v4. Below are the URLs of the pages I am analyzing: https://www.example.com/uiqueId1 https://www.example.com/uiqueId2 https://www.example.com/uiqu ...