简体   繁体   English

从 views.py 访问模板中的变量 - Django

[英]access variable in template from views.py - Django

This is my first time messing with django and I am having trouble passing variables from a view function to a template html file.这是我第一次弄乱 django,我无法将变量从视图 function 传递到模板 html 文件。

views.py视图.py

def index(request):
    try:
        ms_identity_web.acquire_token_silently()
        authZ = f'Bearer {ms_identity_web.id_data._access_token}'
        graph_user_picture = requests.get(settings.USERPHOTO,
                                      headers={"Authorization": authZ})
        file = open("Sample/static/user_iamge"+str(ms_identity_web.id_data.username).split(" ")[0]+".png", "wb")
        file.write(graph_user_picture.content)
        file.close()

        clamdata = context_processors.context(request)
        print(clamdata["claims_to_display"]["preferred_username"])
        userdata = requests.get(settings.ENDPOINT+"/"+clamdata["claims_to_display"]["preferred_username"],
                                    headers={"Authorization": authZ}).json()
        print(userdata)
        return render(request, "flow/index.html", userdata)
    except Exception as e: 
        print(e)
        return render(request, "flow/start.html")

and I am trying to send userdata over to index.html like so:我正在尝试将用户数据发送到userdata ,如下所示:

<div class="ms-Persona-details">
        <div class="ms-Persona-primaryText">{{ userdata["displayName"] }}</div>
        <div class="ms-Persona-secondaryText">{{ userdata["jobTitle"] }}</div>
        <div class="ms-Persona-tertiaryText">{{ userdata["businessPhones"][0] }}</div>
        <div class="ms-Persona-tertiaryText">{{ userdata["userPrincipalName"] }}</div>
      </div>

However, I am getting either no variables showing up on the screen or I get an error like this:但是,我要么没有在屏幕上显示任何变量,要么出现如下错误:

Could not parse the remainder: '["displayName"]' from 'userdata["displayName"]'

I assume I am missing something basic in index.html to pass variables from the views.py to the index.html file我假设我在 index.html 中缺少一些基本的东西来将变量从 views.py 传递到 index.html 文件

this is not how django template works, DTL (django template language) has some rules.这不是 django 模板的工作方式,DTL(django 模板语言)有一些规则。

try this尝试这个

 # views
 return render(request, "flow/index.html",  {'userdata':userdata})
 # template
<div class="ms-Persona-primaryText">{{ userdata.displayName }}</div>

refer this参考这个

https://docs.djangoproject.com/en/4.0/ref/templates/api/#rendering-a-context https://docs.djangoproject.com/en/4.0/ref/templates/api/#rendering-a-context

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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