Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django How to paginate a list of dicts

I have this function where I get data from the Stackoverflow Api as you can see below and I display them in an html table. Is there a way to have pagination for this list of dicts so that 10 results appear on each page?

views.py:

def get_questions(request):
    context = {}
    url = 'https://api.stackexchange.com/2.2/questions'
    params = {  'fromdate':'1525858177',
                'todate':'1525904006',
                'order':'desc',
                'sort':'activity',
                'tagged':'python',
                'site':'stackoverflow'
            }
    r = requests.get(url, params=params).json()
    dataList = []
    for item in r['items']:
        dataList.append({
            'owner': item['owner']['display_name'],
            'title': item['title'],
            'creation_date': datetime.datetime.fromtimestamp(float(item['creation_date'])),
            'is_answered': item['is_answered'], # (yes / no)
            'view_count': item['view_count'],
            'score':item['score'],
            'link':item['link'],
            'answer_count':item['answer_count']
        })

    template = 'questions/questions_list.html'
    context['data'] = dataList
    return render(request,template,context)

questions_list.html:

  <table id="myTable" class="table table-hover">
    <thead>
      <tr>
        <th scope="col">Owner</th>
        <th scope="col">Title</th>
        <th scope="col">Creation date</th>
        <th scope="col">Is answered</th>
        <th scope="col">View count</th>
        <th scope="col">Score</th>
      </tr>
    </thead>
    <tbody>
        {% for d in data %}
      <tr>
        <td>{{ d.owner }}</td>
        <td><a href="{{ d.link }}" target="blank">{{ d.title }}</a></td>
        <td>{{ d.creation_date }}</td>
        <td>{{ d.is_answered|yesno:"yes,no" }}</td>
        <td>{{ d.view_count }}</td>
        <td>{{ d.score }}</td>
      </tr>
      {% endfor %}
    </tbody>
  </table> 
like image 315
Danae Vogiatzi Avatar asked Sep 07 '25 04:09

Danae Vogiatzi


1 Answers

Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links. These classes live in django/core/paginator.py.

Give Paginator a list of objects, plus the number of items you’d like to have on each page, and it gives you methods for accessing the items for each page:

>>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)

>>> p.count
4
>>> p.num_pages
2
>>> type(p.page_range)
<class 'range_iterator'>
>>> p.page_range
range(1, 3)

>>> page1 = p.page(1)
>>> page1
<Page 1 of 2>
>>> page1.object_list
['john', 'paul']

>>> page2 = p.page(2)
>>> page2.object_list
['george', 'ringo']
>>> page2.has_next()
False
>>> page2.has_previous()
True
>>> page2.has_other_pages()
True
>>> page2.next_page_number()
Traceback (most recent call last):
...
EmptyPage: That page contains no results
>>> page2.previous_page_number()
1
>>> page2.start_index() # The 1-based index of the first item on this page
3
>>> page2.end_index() # The 1-based index of the last item on this page
4

>>> p.page(0)
Traceback (most recent call last):
...
EmptyPage: That page number is less than 1
>>> p.page(3)
Traceback (most recent call last):
...
EmptyPage: That page contains no results

I hope these example code snippets helps resolving your query!

like image 145
abhinav Avatar answered Sep 09 '25 02:09

abhinav