0

This is the data coming from my views.py:

gradebook_data = { 'G5A': [...], 'G5B': [...], ... } sections = [ ('G5A': '5-Einstein'), ('G5B': '5-Bohr'), ... ] 

In my template, I want to iterate the sections and display gradebook data inside a for loop like this...

{% for code, section in sections %} <td>{{ gradebook_data.code }}</td> {% endfor %} 

This doesn't work since in Django it tries to do a dictionary lookup for gradebook_data['code'] when what I want to do is to get gradebook_data['G5A'].

Does anybody know a workaround or can point to my mistake? I have spent a whole day just for this already.

This was quite easy to do with PHP's Twig templating library.

1 Answer 1

2

If you're using the Django templating system you can register a custom filter, which has been documented several times on SO for exactly this purpose. For example, here.

Sign up to request clarification or add additional context in comments.

7 Comments

I've thought about making my own filter. I was hoping however, that there is a better way or easier since this is a very common use-case.
Agreed, but it's really pretty easy if you're comfortable with working in Django, and once you've done it once the next time will be easy...
@dashmug in the view function you're really supposed to massage the data more into the form that you later want to consume in the template
@Anentropic After a lot of researching, that's what I realized. Just felt that it added more complexity. In my case, can you suggest a better structure for the gradebook_data above?
@dashmug why not combine them into a single data structure eg gradebook_data = {'G5A': ('5-Einstein', [...]), ...}
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.