1

I need help displaying the cars in my model based on their type. All the cars have their types, e.g SUV, PICKUP, etc. The cars should be displayed by categories, so all cars whose type was set as SUV during creation should all be displayed under SUV. I saw that the regroup built-in can do that, also checked this SO post but still couldn't fix my error.

models.py

class CarType(models.Model):

    type = models.CharField(max_length=200)

    def __str__(self):
        return self.type

class Car(models.Model):
    name = models.CharField(max_length=30, null=False)
    image = models.ImageField(upload_to="media")
    type = models.ForeignKey(CarType)

views.py ``` class CarListView(ListView): model = Car queryset = Car.objects.all() context_object_name = 'cars' urls.py

 url(r'^', CarListView.as_view(), name='cars_list'), 

template

 {% regroup cars by car.type as cars_by_type %}

<ul>
{% for car in cars_by_type %}
    <li><h3 class="header">{{car.grouper}}</h3>
    </h1>
    <ul>
        {% for item in cars_by_type.list %}
          <li>{{ item.name }}</li>
          <li>{{ item.price }}</li>
          <li>{{ item.fuel_type }}</li>
        {% endfor %}
    </ul>
    </li>
 {% endfor %}
</ul>

1 Answers1

1

I believe you just have a small mistake with your call to regroup: you do not need cars.type, simply type. Django expects the "by" argument to be an attribute of "car" and does the lookup for you.

The change would look like this:

 {% regroup cars by type as cars_by_type %}