Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
Reversing results for current page (django paginator generic view)

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Try this

article_list.object_list = list(reversed(article_list.object_list))
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!