1

I'm using the standard django paginator in my generic view like this:

def get_context_data(self, **kwargs):
        context = super(ArchivePagedView, self).get_context_data(**kwargs) 
        article_list = Article.published
        #=====================================
        paginator = Paginator(article_list, self.paginate_by)
        page = self.request.GET.get('page')

        try:
            article_list = paginator.page(page)
        except PageNotAnInteger:
            article_list = paginator.page(1)
        except EmptyPage:
            article_list = paginator.page(paginator.num_pages)


        if 'reverse' in self.request.GET:
            article_list = article_list.reverse() #This doesn't work!
        else:
            article_list = article_list.all()

        context['article_list'] = article_list

        return context

As you can see I want to override article_list with the same list, but in reversed direction, if reverse is in the URL in behind the question mark. That information I get by 'reverse' in self.request.GET. But I get an error: AttributeError: 'Page' object has no attribute 'reverse'. How do I reverse this? (I don't want to have duplicated code in my template.)

Before I fixed this by making an extra context variable (context['reverse']) which says whether the list should be reversed or not, and then I used duplicated code like this:

{% if reverse %}
 {% for article in article_list reversed %}
  ... some code
 {% endfor %}
{% else %}
 {% for article in article_list %}
  ... the same code
 {% endfor %}
{% endif %}

I wonder if there was no better solution.

Asqiir
  • 607
  • 1
  • 8
  • 23

1 Answers1

0

Try this

article_list.object_list = list(reversed(article_list.object_list))
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
  • I tried this in `get_context_data`: `if 'reverse' in self.request.GET: article_list.object_list = reversed(article_list.object_list) context['article_list'] = article_list`. I got an error: `object of type 'reversed' has no len()` – Asqiir Apr 29 '17 at 13:10
  • Thank you for the hint, it should be `article_list.object_list.reverse()` instead of using `reversed`. – Asqiir Apr 29 '17 at 13:12
  • `queryset.reverse()` together with slicing as used by the paginator can change the items in the queryset. To keep the same results but reverse them, you need to use `reversed()` and convert it to a list, so: `list(reversed(article_list.object_list))`. – knbk Apr 29 '17 at 13:44
  • @L_S Unfortunately not :( It reverses everything, not only the current page. That means, the first item is now the last on the last page, not the last on the first page. – Asqiir Apr 29 '17 at 16:39