Home > Mobile >  access variable in template from views.py - Django
access variable in template from views.py - Django

Time:05-05

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 >
        <div >{{ userdata["displayName"] }}</div>
        <div >{{ userdata["jobTitle"] }}</div>
        <div >{{ userdata["businessPhones"][0] }}</div>
        <div >{{ 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

CodePudding user response:

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 >{{ userdata.displayName }}</div>

refer this

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

  • Related