0

I'm learning django from djangobook.com

As an exercise, I'm trying to print all HttpRequest.META dictionary in the form of a table using template.

views.py contains

# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render

def http_headers(request):
    return render(request,'headers.html',{'headers':request.META})

headers.html <-- template

<html><body><table border="1">
{% for k in headers.keys %}
<tr><td> {{ k }} </td><td>{{ headers.k }}</td></tr>
{% endfor %}
</table></body></html>

Output:

<html><body><table border="1">

<tr><td> TMP </td><td></td></tr>

<tr><td> COMPUTERNAME </td><td></td></tr>

<tr><td> wsgi.multiprocess </td><td></td></tr>

<tr><td> RUN_MAIN </td><td></td></tr>

<tr><td> HTTP_COOKIE </td><td></td></tr>
...
...

Problem: Why is it unable to access {{headers.k}}?

djangobook.com says:

Dot lookups can be summarized like this: when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

Dictionary lookup (e.g., foo["bar"])
Attribute lookup (e.g., foo.bar)
Method call (e.g., foo.bar())
List-index lookup (e.g., foo[2])

So, headers.k must first match the dictionary lookup since headers is a dictionary. Right?

What am I missing

claws
  • 52,236
  • 58
  • 146
  • 195

1 Answers1

2

headers is a dictionary, you should iterate over it using items (docs):

{% for key, value in headers.items %}
    <tr><td> {{ key }} </td><td>{{ value }}</td></tr>
{% endfor %}

You mistake is in using {{ headers.k }}, which is basically headers['k'] - request.META don't have k key - that's why you are seeing nothing.

Hope that helps.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • doesn't it first evaluate the value of `k` first and then use it? – claws Aug 04 '13 at 18:03
  • 1
    nope, replace `k` with `HTTP_COOKIE` and you'll see the value. `k` is interpred as a string in this case. Though, if you use `{{ k }}` - you'll see the value of loop variable `k`. That's somewhat confusing, I understand. – alecxe Aug 04 '13 at 18:05
  • 1
    Also see this thread: http://stackoverflow.com/questions/2894365/use-variable-as-dictionary-key-in-django-template – alecxe Aug 04 '13 at 18:07