简体   繁体   中英

Django - passing JSON data to the front-end along with HTML not working

This is my view:

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)})

And then in my template, I have this JS: console.log(userya); but when I try to log it, it gives an error saying:

ReferenceError: userya is not defined

How do I pass JSON to the front-end using Django so that JS can access it?

Note: I am also using DjangoRestFramework and wasn't able to figure out how to do this with DRF either. If anyone knows a way to do it using DRF, that would be great.

Also mote that in my user.html template, I link to a user.js file and in that file is where I am doing console.log(userya) .

您忘记了在模板中使用Django模板变量语法。

console.log({{ userya }});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM