Troubleshooting: Issue with sending JSON data to front-end alongside HTML in Django

Here is the code snippet in question:

import json

class UserPageView(TemplateView):
    def get(self, request, *args, **kwargs):
        obj = User.objects.get(pk=17).username
        return TemplateResponse(request, template="user.html", context={'userya':json.dumps(obj)})

Upon trying to access the JSON data in my template using console.log(userya);, I encounter an error that states:

ReferenceError: userya is not defined

I am seeking guidance on how to successfully pass JSON data from Django backend to the front-end where it can be accessed by JavaScript.

Additionally, I have explored implementing this with DjangoRestFramework (DRF) but have been unsuccessful thus far. Any insights on accomplishing this task with DRF would be greatly appreciated.

It should also be noted that within my user.html template, a link is made to a user.js file where the console.log(userya) statement is being executed.

Answer №1

It seems like you overlooked applying the Django template variable syntax in your template.

console.log({{ userxyz }});

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

Difficulty in displaying modal using jQuery (bootstrap) programmatically

I can't seem to get my bootstrap modal to display manually using my jQuery code <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="container"> <div ...

Enable the choice for Bootstrap collapse animation to be customized

Is there a way to allow users or admins on my website to decide whether or not Bootstrap 4 collapse elements should be animated? The concern is that when many elements are moved by the animation, it becomes less smooth. Therefore, it would be ideal to give ...

Django: the project name's nearest match

I am currently developing a versatile app that requires knowledge of the project's name in which it is being utilized. Accessing the AppConfig (or simply the app name) of the app containing the settings module would already be sufficient for my purpos ...

The function ensure_csrf_token is failing to set the CSRF cookie in the cookies section

I am facing an issue with setting up a CSRF token in my application. Firstly, I have a simple generic view in Python: class GetCSRFToken(views.APIView): permission_classes = [AllowAny, ] @method_decorator(ensure_csrf_cookie) def get(self, ...

Leveraging a JavaScript variable declared outside the function to successfully transfer data to my AJAX function

Every time the enter key is pressed, my AJAX function gets executed. I used to pass a set of javascript variables equal to elements in the HTML (the contents of a text area) as data for the AJAX function. Now, I want these JS variables to hold values from ...

Exploring APIs through Angular components: How to effectively test them

I have recently delved into the world of testing angular projects. While basic unit testing seems to be going smoothly for me, I am encountering difficulties with dependency testing, especially when API services are injected into the component and there is ...

Tips for accessing data from dynamically named inputs within an ng-repeat loop

My objective is to facilitate the process of transferring data from one table row to another. https://i.sstatic.net/2XjSG.png If the information from 2015 remains unchanged in 2016, users should have an efficient method for copying these values into the c ...

How can I subtract a value from an array using node-js?

If we consider a simple scenario where an array totalSpots = [95] contains only one value, and a new booking is made, the goal is to automatically assign one parking spot to the user who booked it. This will involve reducing the value in the array by 1 or ...

A JavaScript function that smoothly scrolls an element into view while considering any scrollable or positioned parent elements

I needed a function that could smoothly scroll a specific element into view with some intelligent behavior: If the element is a descendant of a scrollable element, I wanted the ancestor to be scrolled instead of the body. If the element is within a posit ...

What is the proper way to implement React's Link component from an external npm package to avoid the error message stating, "you should not use link outside router"?

A custom NPM package has been developed to display an icon menu that can be used across multiple projects. Users have the flexibility to provide a 'route' prop to each icon, allowing them to act as links to different pages. Despite importing and ...

Setting state inside the callback function of setState is causing issues with the state not being updated correctly

Having 2 list items, both utilizing the <ListItem /> component with this.props.a = true and this.props.b = true being passed down from their parent components. It's worth mentioning that there are 2 list items in order to ensure that each of the ...

Is there a way to deserialize UTF8 encoded Byte[] in JavaScript within the browser or a Node.js application?

In my C# code, I have defined an event class like this: public class AreaInterventoCreata{ //public properties } var message= new AreaInterventoCreata(); After creating an instance of this class on the server side, I need to inform the subscribed cli ...

Utilizing asynchronous message queues and processing, such as the Amazon Simple Queue Service, within a Django framework

There are a variety of tasks within an application that require actions such as: Sending emails, Posting to Twitter Generating thumbnails for images in multiple sizes Executing a cron job to discover connected relationships A practical method for handli ...

Can you explain the purpose of App.hiddenDivs in jQuery code snippet provided?

Exploring various JQuery performance tips on this insightful website Do you happen to know the significance of App.hiddenDivs ? ...

Implementing a hover effect for a link that triggers a pop-up window, similar to Facebook's feature where hovering over a link reveals options such as sending a message

As a rails programmer, I am working on creating a hover pop-up for links in my project. In this particular scenario, I have an array of users being displayed with various details such as user image and name. My goal is to have a pop-up window appear only w ...

Converting a string containing multiple objects into an array with unique keys

I have a string with multiple objects and I need to add these objects into an array with different values. The data is received from the cart, so the number of objects can vary. For example: {"hidden_product_name":"productA","productId":"120","product_sk ...

Setting Json.Net as the primary serialization tool for a WCF REST service involves a few key steps

Is there a way to modify the default behavior of the WCF DataContractSerializer when serializing and deserializing entities in order to use JSON.NET instead? In my service contract, I am working with the City entity which has IsReference=true for design p ...

Does the "onevent" option get disregarded for jsf.ajax.request in JSF

In my attempt to develop an interactive chat web application using Java EE 7, I am specifically utilizing JSF 2.2 with ajax. The concept involves having a slow pending asynchronous ajax request waiting on the server for each unique client. When a new mess ...

Switch out a section of a hyperlink with jQuery

I am currently working with an 'iframe' that loads up a page containing multiple external links. My goal is to modify these links so that they redirect to 'Youtube' instead. For instance, one of the links on the page appears as follows: ...

The value of req.headers('Authorization') has not been defined

I'm experiencing difficulty with my code as the token is coming back as undefined. Here is the frontend section: export const fetchUser = async (token: any) => { const res = await axios.post('/user/getuser', { headers ...