Issues with Django {{message}} not functioning properly within JavaScript

My problem lies in displaying a message using Django. I have Python set up to allow users to input a message and send it to Google App Engine. My goal is to utilize this message for comparison in JavaScript in order to display the correct image.

Here is the JavaScript code snippet I am using:

var img = document.createElement("img"); 
img.src = "images/150.png";
if ({{messages.get().message}} == "hello"){
  var src = document.getElementById("image1");
  src.appendChild(img);
}

I'm having trouble with messages.get().message as it seems to be throwing a parsing error. The Python code used to post messages in JSON format is shown below:

endef getJSONMessages(callback):
messages = db.GqlQuery("SELECT * FROM Message ORDER BY timestamp DESC LIMIT 1")
strlist = ""
for message in messages:
    if len(strlist)>0:
        strlist += ',' + message.asJSONString()
    else:
        strlist = message.asJSONString()                  
if callback=='':
    return '[' + strlist + ']'
else:    
    return callback+'([' + strlist + ']);'

Any assistance regarding this issue would be greatly appreciated.

Answer №1

attempt

let image = document.createElement("img"); 
image.src = "images/150.png";
if ("{{messages.get.message|escapejs}}" == "hello"){
  let source = document.getElementById("image1");
  source.appendChild(image);
}

Avoid using "messages.get()" in templates. Use "messages.get" instead.

If you opt for

if(messages.get.message == "hello") { ... }

There will be no quotes around the message causing a syntax error to occur.

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

Turning "None" into null within a DRF custom exception process

I am currently diving into Django Rest Framework and I have hit a roadblock with a problem that seems impossible for me to solve. To illustrate, here is an example for better understanding: from rest_framework.exceptions import PermissionDenied from rest_f ...

Switch between two fields using just one animation

I've been experimenting with creating an information tag that slides out from behind a circular picture. To achieve this effect, I created a block and circle to serve as the information field placed behind the image. However, I'm facing a challe ...

Details regarding the enthusiastic execution of Promise callbacks

Is there a specific specification or implementation detail that dictates how quickly the callbacks of a promise are evaluated? For example, if I have: var promise = new Promise((resolve) => { resolve() }); console.log(promise); // there is no p ...

Implement a Threejs labeling method using JavaScript

My knowledge of JS is limited, but I am eager to use JS functions to create labels for Three.js functions. Check out the Demo Link It seems like I'm struggling to create individual labels for each vertex in this scenario. Why does it only generate o ...

A technique in JavaScript that allows for assigning object property values using an external variable

I need to clarify my situation with a code example const faultLine = new google.maps.Polyline({ paths: [ new google.maps.LatLng(49.95, -128.1), new google.maps.LatLng(46.26, -126.3), new google.maps.LatLng(40.3, -125.4) ] }); ...

Steps to eliminate a specific value from an array

I need to remove values with the .html extension from an array in JavaScript, leaving only those items that do not have the .html extension. Here's my current code: main.js: var arr=["test1.html","power.html","main.html","save.md","kart.html","taste ...

Tips for Hosting Multiple Websites with Unique Domain Names on One Web Hosting Account

I am currently seeking recommendations for mechanisms that would work well in my specific situation. After trying out the iframe solution, I realized it was not suitable due to responsiveness issues on the website. I then looked into using a responsive i ...

Run a JavaScript function multiple times in the code behind using C#

My challenge involves using a datatable and executing a JavaScript function for each row, with different values each time. For every row, the JavaScript function is executed and the result is sent back to the code behind using a web method. However, with ...

Is there a way to copy this JavaScript variable and modify the displayed text?

I am working on a JavaScript code that is used to create a basic news page with a filter from a mySQL database. The code generates the heading, main content, and date created for each news item. I now need to add a "read more" link at the bottom of each ne ...

I'm curious if there is a specific jQuery event that triggers right before an element loses focus or right before the next element gains focus

I am facing a situation where I have two input elements in a form that are closely connected. The first element triggers an ajax call to check for existing data in the database when the user tries to move away from it, while the second element opens a moda ...

Switching data between two views in Codeigniter and updating the database

I am currently working on building a fantasy football site and I need to create a substitution system. My view displays 11 starting players and 4 on the bench. Below is the structure of my fantasy team table. teamID | fantasyteam | userID | GK1 | GK2 ...

Executing leadership commands on AWS ECS (such as running Django migrations)

Currently, our Django APP is being deployed on AWS Elastic Beanstalk. During this process, we run django db migrations using container commands and ensure that the migrations are only executed on one instance by employing the "leader_only" restriction. We ...

Achieve the central element while scrolling on the window

What am I doing wrong? I've been attempting to target the #second element on scroll Here is an example with console.log CODEPEN EXAMPLE $(window).scroll(function(){ var section = $("#second").offset().left, scrollXpos = $( ...

Unable to retrieve information from JSON using jQuery's AJAX method

My journey with learning JSON using jQuery has hit a bump in the road. Despite spending two days and going through various tutorials on YouTube and blogs, I'm facing a challenge. The JSON structure presented in the tutorials differs from the one I hav ...

The AWS S3 CreatePresignedPost function is failing to generate certain essential fields

Currently, I am facing an issue with the generation of a presigned post for allowing browser privileges to upload/delete a specific file from a bucket. It appears that the createPresignedPost function is not populating some of the required fields, whereas ...

Preventing PCs from accessing a specific webpage: A step-by-step guide

I am currently using the code below to block phones: if { /Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i .test(navigator.userAgent)) { window.location = "www.zentriamc.com/teachers/error ...

Is there a way to activate this function through the URL?

I have some Javascript code on my webpage that triggers a popup to open. Now, I am looking for a way to generate a URL that will automatically open the popup. I've come across suggestions to use parameters in the URL, such as adding ?parameter=true. H ...

Building with inline elements in Django

Within my Django 1.7 project, I am working with two closely connected models: Train and Passenger. The Passenger model has a ForeignKey linking it to the Train model. I am looking to create a view where users can add passengers and designate which train ...

When the Promise object is assigned to the img [src], the image may occasionally be set to null

I incorporate Angular into my Electron application. One of the components in my app contains an array called files, where each element is an object with a member named preview. This preview member is a Promise object that returns a file:// object. <mat- ...

What is the most secure and accurate method for altering an object's state variable in React?

Behold, the code below has been tried and tested, effectively updating the state variable of the object: import { useState } from 'react' import './App.css'; function App() { const [config, setConfig] = useState({ status: & ...