Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate objects in Django template?

Tags:

django

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?

like image 479
FeFiFoFu Avatar asked Sep 01 '25 10:09

FeFiFoFu


1 Answers

better approach - cleaner code, apart from db effeciency:

alphabet = ['A','B','C','D','E','F','G', ..]

brands_list = []
for letter in alphabet:
    letter_ = {'cars': Cars.objects.filter(brand__startswith=letter), 'letter': letter}
    brands_list.append(letter_)

return render(request, 'cars/home.html', {'brands': brands_list})

template

{% for brand in brands %}    
    {{ brand.letter }}    
    {% for car in brand.cars %}
        <a href="{{ car.link }}">{{ car.name }}</a><br>
    {% endfor %}
{% endfor %}
like image 165
doniyor Avatar answered Sep 03 '25 06:09

doniyor