Wincij
Wincij

Reputation: 111

Django dictionary not passed?

Trying to pass python dictionary to my django template. But it seems to not be passed while rendering. I have read documentation and few sites, but can't find solution. It must be simple...

#views.py
def home(request):
    context = {}
    links = getLinks()
    for link in links:

        splited = getRate(link).split()
        # print(splited)
        key = splited[1]
        context[key] = float(splited[0])
    print(context)
    return render(request, 'home.html', context)

home.html:

{% for key, value in context.items %}
<a href="{{key}}">{{value}}</a>
{% endfor %}

I print dictionary in my terminal, so it definitely exists and contains everything I need. But can't refer to it in my template.

Upvotes: 0

Views: 349

Answers (1)

Flux
Flux

Reputation: 10920

The reason is that the template does not know about the name context, so in {% for key, value in context.items %}, context.items does not refer to anything.

That means you need to pass the correct dictionary to the template:

# views.py
def home(request):
    data = {}
    links = getLinks()
    for link in links:
        splited = getRate(link).split()
        key = splited[1]
        data[key] = float(splited[0])
    return render(request, 'home.html', {'context': data})  
    # Now, 'context' will actually mean something to the template.

Now that you know where the mistake is, I suggest that you not name your template variable context.

Upvotes: 2

Related Questions