Roman
Roman

Reputation: 13

Using dictionary to print values to HTML table creates empty table

I'm trying to render a table in a webpage using a dictionary of dictionaries. Seems like a simple enough task, but so far I've had no success.

So far, I've tried the following code:
Template:

<table>
      <thead>
        <tr>
          <th>Email</th>
          <th>Name</th>
          <th>Workplace</th>
          <th>Contact Number</th>
          <th>User type</th>
        </tr>
      </thead>
      <tbody>
        {% for key,value in contacts.items %}
        <tr>
          <td>{{ key }}</td>
          <td>{{ value.name }}</td>
          <td>{{ value.workplace }}</td>
          <td>{{ value.contact }}</td>
          <td>{{ value.user_type }}</td>
        </tr>
        {% endfor %}
      </tbody>
</table>

And my contacts is of the following format:

{
'[email protected]': {'workplace': 'SRK Films', 'user_type': 'company', 'name': 'SRK', 'contact': '-'},
'[email protected]': {'user_type': 'campus', 'workplace': 'bchjb', 'contact': '1478529631', 'name': 'Pry'}
}

I'm sending the variable to template through the following:

return render(request, 'maintainer/mcontact.html',contacts)

All I'm getting is the header cells that I explicitly wrote. The rest of the table data is empty. It shows a "No data available in table" message. I'm printing contacts to stderr so I know the variable has the correct values. Am I missing something else? I don't understand what else I should do. Any help is appreciated since I'm very new to Django.

Upvotes: 1

Views: 224

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You should not pass contacts as the root context dictionary, since that means that you now constructed variables like [email protected] and [email protected] in your template.

What you should do is wrap it in a dictionary with contacts as key, like:

return render(request, 'maintainer/mcontact.html',{'contacts': contacts})

Now we will thus make a variable named contacts in the template, and you can then iterate over the items of that dictionary.

Note that Django does not know the name of the variable you passed to the render(..) call. In fact if you use a dictionary literal like here, there is not even a variable, it is just an expression. The render(..) [Django-doc] just takes a context with:

context

A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.

So the key of the items in that dictionary are the names of the variable(s) and the values are the corresponding values that will be bound to these template variable(s).

Upvotes: 2

Related Questions