In Django 1.9, I have a database table that contains car brands. I am trying to build an index (like one found at the back of a textbook) of car brands. For example:
A
Aston Martin
Audi
...
B
Bentley
BMW
...
Here is code from my view.py:
def home(request):
car_index = {}
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N',
'O','P','Q','R','S','T','U','V','W','X','Y','Z']
for letter in alphabet:
car_index[letter] = {}
car_index[letter]['title'] = letter
car_index[letter]['brands'] = Cars.objects.filter(brand__startswith = letter)
return render(request, 'cars/home.html', {'car_index':car_index})
Here is code from my home.html template:
{% for each in car_index %}
{{ each.title }}
{% for brand in each.brands %}
<a href="{{ brand.link }}">{{ brand.name }}</a><br>
{% endfor %}
{% endfor %}
In view.py, I have tried .values()
in the queryset, .items()
in the template context. In the template, I have tried car_index.items
, each.brands.items
, each.brands[0]
. Nothing works. With the code above as is, I get the titles: E D X I A U H B T S N K Q Z J Y W V O L R F G P C M, but no links. (I know how to sort, but working on links first)
I have read:
https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#for
how to iterate through dictionary in a dictionary in django template?