简体   繁体   中英

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.

views.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:

<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

this is not how django template works, DTL (django template language) has some rules.

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

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