Tips on sending template variables to JavaScript

Greetings, I am currently facing an issue with passing a template variable to javascript in order to create a chart. Unfortunately, Django treats all js files as static files which means that dynamic template variables are not accessible within javascript.

I attempted the solution mentioned here:

passing template variables to javascript

However, it didn't resolve the issue as only one variable could be successfully passed while the others couldn't.

def profile(request,username):
    try:
        u = User.objects.get(username=username)
        questions = Question.objects.filter(user=u)
        answers = Answer.objects.filter(user=u)
        docs = Document.objects.filter(user=u)
    except User.DoesNotExist:
        pass
    return render(request,"auths/profile.html",locals())

In addition, my profile.html contains the following code as per the suggestion in the aforementioned link:

<input type="hidden" value="{{ u.username }}" id="username" />
<input type="hidden" value="{{ docs.count }}" id="docs" />
<input type="hidden" value="{{ questions.count }}" id="questions" />
<input type="hidden" value="{{ answers.count }}" id="answers" />


{% block extra %}
    <script type="text/javascript">
        var user = document.getElementById("username").value;
        var docs = document.getElementById("docs").value;
        var questions = document.getElementById("questions").value;
        var answers = document.getElementById("answers").value;
    </script>

   <script type="text/javascript" src="{% static 'highcharts.js'%}">      </script>
   <script type="text/javascript" src="{% static 'highcharts-3d.js'%}"></script>

   <script type="text/javascript" src="{% static 'chart.js' %}"></script>


{% endblock %}

Furthermore, there is a snippet from my chart.js file where I assign the data to be displayed on the chart:

series: [{
  type: 'column',
  name: 'User Profile',
  data: [
      ['Questions',   questions],
      ['Answers',   answers],
      ['Documents',  docs]
  ]
}]

The challenge here remains that only one variable is being successfully passed while the remaining ones are not, resulting in the failure to render the desired chart. Any advice or suggestions from fellow developers would be greatly appreciated.

For reference, I am using Django 1.9 along with highcharts for this project.

Answer №1

After exploring my own question, I finally identified the issue. It turns out that the chart values were in numerical format, while I was treating them as strings. The solution was simple - I needed to convert those string values into numbers using JavaScript typecasting.

Here is a snippet from my chart.js code where I made the necessary adjustments:

series: [{
  type: 'column',
  name: 'User Profile',
  data: [
      ['Questions',   Number(questions)],
      ['Answers',   Number(answers)],
      ['Documents',  Number(docs)]
      ]
}]

By converting the strings to numbers, the chart displayed correctly!

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

Utilizing the jQuery plugin 'cookie' to retain the current tab selection on a webpage

Is it possible to provide a detailed explanation on how I can utilize the jQuery Cookie plugin to maintain the selected tab throughout my entire website? Here is the current JavaScript code in JSFiddle format: http://jsfiddle.net/mcgarriers/RXkyC/ Even i ...

Adjust puppeteer window dimensions when running in non-headless mode (not viewport)

Is there a way to adjust the browser window size to match the viewport size in Chrome(ium)? When only setting the viewport, the browser can look awkward if it is not running headfully and I want to visually monitor what's happening within the browser ...

Can you please guide me on how to effectively configure a personalized time zone using MUI date picker combined with dayjs?

In my application, the user's time zone is supplied by the server instead of being determined by the browser's settings. When I receive a Unix timestamp from the server and pass it to the date picker, the displayed date is incorrect because the ...

One beneficial aspect of utilizing JavaScript closures for events is when defining a click event

There are two common ways to write code in JavaScript that accomplish the same task: Option A. SomeObject.prototype.hideElement = function(e, element){ e.stopPropagation(); hide(element); } Option B. SomeObject.prototype.hideElement = function( ...

How can you integrate jquery ajax in WordPress?

Recently, I started learning about jquery and have been following a tutorial on creating instant search using jquery. The tutorial can be found here. Now, I am trying to implement this on my WordPress site, but it seems like things work differently when d ...

Creating a variable in Node.js to serve as the name of a nested element within an object

Check out the object I have: obj = { "FirstName": "Fawad", "LastName": "Surosh", "Education": {"University": "ABC", "Year": "2012"} } Take a look at my node.js script: var nodeName = 'Education.Year'; obj.nodeName; // ...

breezejs: Non-scalar relationship properties cannot be modified (Many-to-many constraint)

Utilizing AngularJS for data-binding has been smooth sailing so far, except for one hiccup I encountered while using a multi-select control. Instead of simply adding or removing an element from the model, it seems to replace it with a new array. This led t ...

Tips for customizing the checked color of Material UI Radio buttons

If I want my radio button to be green instead of the default options (default, primary, secondary), how can I achieve that? I attempted to override the color using the classes prop like this: const styles = theme => ({ radio: { colorPrimary: { ...

Struggling to get Angular to properly sanitize inputs using ng-bind-html

I've been struggling to figure out the issue in my code for an entire day with no success. At this point, I'm reaching out for help. My problem arises when trying to utilize ng-bind-html-unsafe within a template. As a newcomer to Angular, it&apos ...

No data found in cleaned_data

I am facing a perplexing issue where changes made in a specific inline formset are not being saved, despite using the same code that works for other inline formsets. Upon inspection, I noticed that the form "AtLeastOneFull" always has empty cleaned_data, e ...

Engage in Step 2: Receive a response from the server via AJAX request

I've been utilizing AJAX in conjunction with the Play 2 framework to send requests and execute actions on the server side. Learn how to make an AJAX request with a common button in Play 2.x Troubleshooting Jquery and Play Framework 2 JavaScript rout ...

Sort slider items using Show/Hide feature in bxSlider

I am using a bxslider on my website with specific settings: $('#carousel').bxSlider({ slideWidth: 146, minSlides: 2, maxSlides: 6, speed:500, adaptiveHeight: true, moveSlides:3, infiniteLoop : false, hideContr ...

In the realm of Laravel, Vue, and Javascript, one may question: what is the best approach to omitting a key

When working with JSON data, I encountered a problem where leaving some keys unfilled resulted in incorrect results. I want to find a way to skip these keys if they are not filled. I have shared my code for both the backend and frontend below. Backend La ...

Using Flask and jQuery, learn how to toggle the visibility of a reply text box

After a break from using HTML/JavaScript, I find myself a bit puzzled about how to handle this. I'm working on creating a reddit-like clone with Flask. I've reached a point where I can add child comments to any comment and have them display nic ...

Tips for adjusting the height of a Safari extension during runtime

After successfully developing a Safari extension, I am facing an issue with adjusting the width and height of the popover dynamically at runtime. Can anyone provide insights on how to modify the dimensions of the popover based on its content? ...

Discovering the initial vacant row within an HTML table with Javascript

Below is a snippet of code that generates a table with 6 rows. The last two rows remain empty. The JavaScript logic in the code correctly determines and displays the total number of rows in the table. I'm currently looking for a way to identify the ...

Unveiling the Magic: Transforming Objects into HTML Attributes using AngularJS

I have been working on developing a highly dynamic ng directive that creates tables based on a given data array and configuration object. I am looking for a way to assign attributes dynamically based on an object within the scope. For example, if I have an ...

Is there a way to dynamically create a property and assign a value to it on the fly?

When retrieving data from my API, I receive two arrays - one comprising column names and the other containing corresponding data. In order to utilize ag-grid effectively, it is necessary to map these columns to properties of a class. For instance, if ther ...

Getting the value of a repeater label in JavaScript can be achieved by following these

Here is my javascript code: function btnEditClick() { alert(document.getElementById('<%=LblRefPhyID.ClientID %>').value); } <asp:Repeater ID="repeaterRefPhysicianList" runat="server"> <ItemTemplate> < ...

Can routes be nested in React components?

I'm curious to know if there's a way to integrate nested routes in React, where the Navbar component serves as the parent for dashboard and properties. <Router> <Routes> <Route path='/' element={<Home />} /> ...