How can I properly include Django's objects in my JavaScript within the templates?

class KcalDetailView(DetailView):
    model = User
    context_object_name = 'target_kcal'
    template_name = 'kcalculatorapp/detail.html'
  
    def get_context_data(self, **kwargs):
        kcl = self.request.user.kcal
        context = super().get_context_data(**kwargs)

        i = 0
        kcal_list = []
        while i < 13:
            i = i + 1;
            if kcl.goal == 'diet':
                kcal_list.append((kcl.weight -round((500/7000)*i,2) ))
            else:
                kcal_list.append((kcl.weight + round((500 / 7000) * i,2)))

        context['kcal_list'] = kcal_list

        return context

https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/line-labels

this chart use.

templates.html

    .
    .
    .
<script>
    .
    .
    .
        series: [{
            name: 'a',
            data: {{  kcal_list }}     // this !!!
        }]
    });
</script>

For example kcal_list = [ 10, 13, 15, 16, 20 ] It's in the form of a list.

And data: [10, 13, 15, 16, 20] Why does it look like this?

data : {{kcal_list}} is not possible?

What should I do?

Answer №1

The value of the {{variable}} is directly inserted into the HTML code. If you check the page source, you'll see that it's not actually a dynamic variable but plain text.

However, you can still employ this kind of substitution in your JavaScript code.

<script>
    series: [{
        name: 'b',
        data: "{{  numbers_list }}"     // demonstrate here !!!
    }]
});
</script>

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 name of the inherited class that invoked the function?

I am looking for a way to determine the name of the class of an object from within a function that called that function. My approach involves utilizing John Resig's class inheritance concept. For instance var CoreStuff = Class.extend({ log: function ...

How can I delete the visuals and objects from my mind in Three.js?

I need to place a specific number of circles on the scene. var radius = 1; var segments = 32; var circleGeometry = new THREE.CircleGeometry( radius, segments); function generateCircles(){ //scene.remove(circle); var count=0; while (1000> count ...

What are the most efficient methods for implementing a deep level update in a React Redux store?

Currently experimenting with Redux and constructing an application driven by dummy data. Within my application, there exists a component labeled "birdInfo" which holds some state within the Redux store. https://i.sstatic.net/Msdu5.png To update the store ...

execute a function from a separate file in a node.js environment

How can I call the /getJobs endpoint inside the job.js node script? I'm currently using this approach, but I'm receiving an error stating "$ is not defined". job.js var jobSchedule = function (time, jobId) { var params = { "id": jo ...

Images flicker as they transition, intervals are causing havoc

I am creating a random fade effect for images within a specific container. Below is the HTML code for the container: <div id="container" class="container"> <img src="http://farm3.static.flickr.com/2610/4148988872_990b6da667.jpg" /> &l ...

When you try to create an array of JSX components in React, using objects as child elements is not allowed

I have made the transition of a project from the old React.createComponent to the new ES6 class definition. Below is an example of one component that I updated: class UpdatedComponent extends React.Component { constructor(props) { super(props) ...

Completing Forms Automatically with AngularJS

Hello! I'm just starting out with ng and I need to make an autocomplete textbox that will initiate an AJAX call when the text is changed. The catch is that the minimum length required to trigger the AJAX call is 3 characters. However, once the user en ...

Cutting an image in ReactJS using the HTML5 canvas feature

Seeking a way to crop images in reactjs without relying on any external library. The goal is for users to upload an image and perform cropping using raw JavaScript, then replace the uploaded image. How can this be achieved without the use of libraries? Loo ...

Check through an array for any updates whenever a function is called and my react state is altered

I am currently working on a project related to playlists. My goal is to display the image attached to each song whenever that song is clicked from the playlist. Here is the code I have so far... const Component = () => { const value = useContext(DataC ...

Adjusting the display location of the icon

I'm working on an AngularJS table and I need to add a text field for filtering/searching. However, the automatically generated icon is not displaying in the right place. Here is my current view: <table> <theader> <tr> < ...

Combining data from an API using Vue for seamless integration

I need to extract data from an API, such as imdbID, and then append ".html" to it in order to create a variable that can be placed inside the href attribute of a button. However, I am facing difficulties in achieving this. Thank you in advance for your hel ...

Tracking ajax calls with piwik: A step-by-step guide

I'm curious about how to enable piwik to track ajax requests. I know there is an API available, but I'm unsure about the exact steps I need to take in order to view ajax loaded pages in the dashboard. Could it be something like this: _paq.push( ...

Implementing dynamic title insertion into a popover element using jQuery

My goal is to assign a title to my popover object in a local project. I have already included the following files: bootstrap.css v4.2.1 jquery.min.js v2.2.0 bootstrap.min.js v4.2.1 popper.min.js v1.11.0 Initially, there was a basic button present. <i ...

Error: JSON parsing encountered an unexpected character "D" at position 1

When I call a python script as a child process from my node.js app to extract data from an uploaded file, I encounter the error 'UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token D in JSON at position 1" when uploading the file thro ...

When the horizontal scroll is turned off, it also disables the functionality of my mobile-friendly

I came across a helpful post on StackOverflow that suggested using the following code to disable horizontal scrolling: html, body { overflow-x: hidden; } This solution did resolve my issue of horizontal scrolling, but unfortunately it caused problems ...

Issue with Calendar Control not loading in Internet Explorer 9 when using ASP

I have been trying to incorporate a calendar control in my code that selects a date and returns it to a text field. It worked perfectly fine on browsers prior to IE 8, but I'm facing issues with IE 9. Can someone help me troubleshoot this problem and ...

How is it possible for me to receive a userId duplicate key error when the primary key in my model is not assigned to the user?

I am working on an Interactions model that extends the default Django user model, with messageId set as the primary key. models.py: class Interaction(models.Model): messageId = models.TextField(max_length=5000, primary_key=True, unique=True) user = model ...

What is the best way to change JSON into a key-value dictionary with TypeScript?

Here is a JSON example that I am working with: { "MyTest:": [{ "main": { "name": "Hello" }, "test2": { "test3": { "test4": "World" }, ...

Google Maps GeoCoding consistently relies on the language settings of the browser in use

I have implemented the Google AJAX API loader to retrieve information in German by loading the maps API using this code: google.load("maps", "2", {language : "de"}); Despite trying variations such as deu, ger, de, de_DE, and ...

Is it secure to use console.time() in a Node.js environment?

Looking at a small snippet of node.js code, here's what I have: console.time("queryTime"); doAsyncIOBoundThing(function(err, results) { console.timeEnd("queryTime"); // Process the results... }); Running this on my development system gives m ...