Naveen Kumar
Naveen Kumar

Reputation: 1626

Accessing variables in view - Django template

I am totally new to python and django. I want to know how to access the dictionary variables in template. I tried few ways but nothing worked out. if i print the variable in the template i receive from my view function this is what i get

{'BSE:INFY': {'instrument_token': 128053508, 'last_price': 1150.3}, 
'NSE:INFY': {'instrument_token': 408065, 'last_price': 1150}}

I want to loop through the ltp and print something like this

BSE:INFY - 1150.3
NSE:INFY - 1150

EDIT

For ex : in my template

{{ ltp }}

gives the output

{'BSE:INFY': {'instrument_token': 128053508, 'last_price': 1150.3}, 
'NSE:INFY': {'instrument_token': 408065, 'last_price': 1150}}

now how do i loop through them and print something like above mentioned ?

Upvotes: 0

Views: 3234

Answers (2)

Sijan Bhandari
Sijan Bhandari

Reputation: 3061

You can access any dictionary item into your django template as {{dict.key}}.

Suppose you have following dictionary in your views:

 dict = {'first_name':'first','last_name':'last'}

You need to send your dictionary item as follows:

 return render(request, self.template_name, {'data': dict})

To access your dictionary data in template, you can use

    {{ data.first_name }}

To iterate over dictionary, you can do following

{% for key, item in ltp.items %}
    {{ key }} : {{item.instrument_token}}, {{ item.last_price }}
{% endfor %}

Upvotes: 1

Rakesh
Rakesh

Reputation: 82795

You can use a for loop in the django template.

EX:

{% for key, value in ltp.items %}
    {{ key }} - {{ value.last_price }}
{% endfor %}

Upvotes: 2

Related Questions