Wessi
Wessi

Reputation: 1812

Django ordering with pagination

I have implemented ordering and pagination in a generic ListView:

class CarList(LoginRequiredMixin, ListView):
    model = Car
    paginate_by = 30

    ordering = 'car_id_internal'

    def get_ordering(self):
        return self.request.GET.get('ordering', 'car_id_internal')

And in my template:

<thead>
        <tr>
            <th><a href="{% url 'car_list' %}?ordering=car_id_internal">Internal car ID</a></th>
            <th><a href="{% url 'car_list' %}?ordering=type">Type</a></th>
            <th><a href="{% url 'car_list' %}?ordering=brand">Brand</a></th>
        </tr>
    </thead>

and the pagination in the template:

{# .... **Now the pagination section** .... #}
{% if is_paginated %}
    <div class="pagination" style="width:100%">
        <span class="page-links">
            <div class="col-sm-2">
            {% if page_obj.has_previous %}
                <a href="/feriehus?page={{ page_obj.previous_page_number }}">Forrige side</a>
            {% endif %}
            </div>
            <div class="col-sm-2">
            <span class="page-current">
                Side {{ page_obj.number|unlocalize }} af {{ page_obj.paginator.num_pages|unlocalize }}
            </span>
            </div>
            <div class="col-sm-2">
            {% if page_obj.has_next %}
                <a href="/feriehus?page={{ page_obj.next_page_number }}">Næste side</a>
            </div>
            {% endif %}
        </span>
    </div>
{% endif %}

This works fine, however when I click next page it reverses to ordering by car_id_internal. I would like it to keep the ordering selected on the first page such as type when I go to the next page. Is this possible with Django? I'm using Django 1.9.

I hope someone can help.

Upvotes: 0

Views: 758

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599778

You need to pass the current ordering value into the template and use it in the next/previous page links:

class CarList(LoginRequiredMixin, ListView):
    def get_context_data(self, *args, **kwargs):
        context = super(CarList, self).get_context_data(*args, **kwargs)
        context['current_order'] = self.get_ordering()
        return context

...

<a href="/feriehus?ordering={{ current_order }}&page={{ page_obj.previous_page_number }}">

and so on.

Upvotes: 2

Related Questions