[Answered ]-How to allow users to submit a get request to a class View and order item?

1👍

Since you are already using django-filter you should use the OrderingFilter to allow the user to select an order:

class VehicleFilter(django_filters.FilterSet):
    min_price = django_filters.NumberFilter(
        field_name="price", lookup_expr='gte')
    max_price = django_filters.NumberFilter(
        field_name="price", lookup_expr='lte')
    release__gt = django_filters.NumberFilter(
        field_name='year', lookup_expr='gte')
    release__lt = django_filters.NumberFilter(
        field_name='year', lookup_expr='lte')
    
    o = django_filters.OrderingFilter(
        # tuple-mapping retains order
        choices = (
            ('price', 'Price:Highest to Lowest'),
            ('-price', 'Price:Lowest to Highest'),
        ),
        fields={
            'price': 'price',
        },
    )

    class Meta:
        model = Vehicles
        fields = ['make', 'brand',
                  'transmission', 'fuelType', 'bodyType']

Note: Your indication for "Highest to Lowest" and "Lowest to Highest" appears wrong? For -price it should be "Highest to Lowest"
etc.

Next since you are using django-filter instead of using ListView simply use the FilterView provided by django-filter. This inherits from MultipleObjectMixin (which is what ListView also inherits from) and hence supports all of the features ListView does (pagination , etc.):

from django_filters.views import FilterView


class GarageListView(FilterView):
    model = Vehicles
    filterset_class = VehicleFilter
    template_name = 'garage/garage.html'
    context_object_name = 'cars'
    ordering = ['-price']

Now you can simply remove the form you previously had for ordering, the ordering field would show up with the filters form. Also instead of looping over filter.qs you should now loop over object_list or as per your context_object_name it would be cars: {% for v in cars %}..{%endfor%}

Leave a comment