Unable to utilize dictionary sent from Django to the template

Below is a Python dictionary that I am sending to a template:

mydict = {
    "ABC": {
        "target_weight": 1,
        "target_ra_weight": 2
    },
    "XYZ": {
        "target_weight": 3,
        "target_ra_weight": 4
    },
    "JKL": {
        "target_weight": 5,
        "target_ra_weight": 6
    }
}
return render(request, 'template.html', {'mydict': mydict})

I'm having trouble assigning this data to a JavaScript variable and accessing its content. I've attempted the following in the JavaScript section of my template:

var mydict = {{ mydict }};
> Uncaught SyntaxError: unexpected token {

var mydict = {{ mydict|safe }};
> Uncaught SyntaxError: unexpected token {

var mydict = {{ mydict|escapejs }};
> Uncaught SyntaxError: unexpected token {

The code below allows me to create the variable, but attempting to access it ((e.g., console.log(mydict)) results in an error:

var mydict = JSON.parse('{{ mydict }}');
console.log(mydict);
> Uncaught SyntaxError: unexpected token { in JSON at position 1
// same thing happens when using |safe or |escapejs

Answer №1

To properly handle the data, utilize JSON instead of a dictionary. You can achieve this by employing the json.dumps function:

import json

mydict = {
    "ABC": {
        "target_weight": 1,
        "target_ra_weight": 2
    },
    "XYZ": {
        "target_weight": 3,
        "target_ra_weight": 4
    },
    "JKL": {
        "target_weight": 5,
        "target_ra_weight": 6
    }
}
return render(request, 'template.html', {'mydict': json.dumps(mydict)})

In your template file, ensure to include the following code:

var mydict = JSON.parse('{{ mydict|safe }}');

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

Exploring the depths of Django's background processing capabilities

I am a beginner in Django and I am struggling to grasp the concept of implementing background processes. Here is an example from my code: model.py class Person(models.Model): name = models.CharField(max_length=23) math_grade = models.IntegerField( ...

Creating a dropdown button with three dots in a table row using jQuery

I've been working with tables and I'm trying to create a dropdown list with 3 dots in each table row. I've experimented with a few libraries and custom dropdown options, but none of them seem to be working properly. What I'm looking fo ...

What is the syntax for implementing a nested for loop in JavaScript within this particular scenario?

var entries = [ { "item": "something", "steps": [{ "node": {"name": "test0"}, "status": {"name": "test"}, "time": {"name": "test"} },{ "node": {"name": "test1"}, ...

Is there an issue with implementing autosuggestion and tagging functionalities in jQuery?

My script is designed to suggest values based on user input and then convert the selected value into a tag. However, when a value is selected from the drop down menu, only the first 2 or 3 characters are tagged. You can see the script in action on js fiddl ...

The file upload functionality is functioning properly when tested with Postman, however, it is encountering issues

I am currently facing an issue with file upload. I am using Angular in the front-end and Java in the backend to upload images to an S3 bucket. The Java code seems fine as I tested the upload URL on Postman and it worked smoothly. Here is a screenshot from ...

When extracting information from JSON, storing unidentified data member names in a generic Dictionary<string, object> is a common practice

I am working with Swagger JSON data and using Newtonsoft.JSON to deserialize it. My object definition looks like this: public class WebService { public string swagger; public Dictionary<string, object> AllOthers; } The JSON data includes th ...

SSL Django Cookie Cutter

Is there a way to turn off the automatic SSL redirect feature in pydanny's django cookie cutter? Even after commenting out the line below, it doesn't seem to work? SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=False) ...

When expanding a template page, all I see is a void of

Whenever I try to extend the polls/index page to my main blog/index page, I end up with a blank page. Why is that happening? blog/index.html {% extends "polls/index.html" %} <!doctype "html5"> <html> <head> ..... ...

Unable to assign the value of "textcontent" to null property

There is an issue that occurs specifically with this code snippet, generating the error message: Cannot set property 'textcontent' of null for this line: document.getElementById("days").textContent = d; function countdown() { var now = new ...

"Learn how to use socket.io in conjunction with the express generator to create individual sockets for each unique link

I'm working on a typical express-generator app where I have some code in my controllers folder: router.get('/:id([A-Za-z0-9_]{5,25})', function(req, res, next) { res.render('my-page.html', { title: 'Messag ...

Getting assistance with Go Lang - Reaching an Array/Slice of interfaces

I am currently working on decoding dynamic or random JSON responses in GO, especially when dealing with nested data. body, _ := ioutil.ReadAll(response.Body) resp := make(map[string]interface{}) err = json.Unmarshal(body, &resp) fmt.P ...

Adding Rotation to a group in Three.js using a pivot point

I'm currently in the process of constructing a Rubik's Cube using Three.js. My method involves grouping all the small cubes that need to be rotated together and then performing the rotation on the group as a whole. To determine the pivot point fo ...

Arrange data in JSON file based on job title (role name) category

My current code successfully outputs data from a JSON file, but I'm looking to enhance it by organizing the output based on the "Role Name". For example, individuals with the role of Associate Editor should have their information displayed in one sect ...

How can I retrieve PHP code output within a jQuery function?

In my CodeIgniter project, I am trying to generate a unique ID using PHP by calling the random_string() function: function coding(){ echo random_string('unique'); } I want to use the result of this function in an AJAX jQuery call (to be use ...

Tips on displaying a selected choice | Utilizing Material UI Autocomplete

I have successfully fetched data from an API and used it as options in Material UI Autocomplete. However, when I select an option and send it back to the API using a POST request, the selected category is displayed as a number (0) instead of text, as shown ...

If the request is made via AJAX, the response will be in JSON format

Looking for a way to deliver JSON data if it's an AJAX call, otherwise serving HTML content. Not relying on any framework or templating system... This is my approach in the initial page: $.ajax({ type : 'GET', dataType: 'json ...

Do we need to use initializeApp() from Firebase 9 when setting up email login?

Similar Topic: Exploring the Fun of Firebase's initializeApp(config) Function When integrating Gmail login, is it necessary for an app to invoke intializeApp()? Although the documentation specifies that a config object must be provided to initializ ...

Fixing PNG Fading Issue in Internet Explorer 8

I am currently utilizing the jQuery Cycle plugin to produce a fading animation effect. While this works perfectly on most browsers, I have encountered an issue with PNG files containing semi-transparent pixels in Internet Explorer 8. These partially transp ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

What is the best way to store and retrieve information in JSON format?

Looking to create a forum using Angular JS and in need of advice on creating JSON data files to store and retrieve information. One key requirement is the ability to add new data directly from the browser, without modifying the data file itself. Any help ...