How to show some news instead of whole news that i grab from an API


(Nehat Khan) #1

Here is my code. The problem I am facing now is when i call the dictionary " coinprice" in my template it shows whole news and the page get full. I want to use paginator or show only given news news just like we show in list = [0:10] and it shows 10 articles of news

from django.shortcuts import render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
import requests, json, itertools

def home (request):
    #Grab Crypto News 
    api_requests = requests.get('https://min-api.cryptocompare.com/data/v2/news/?lang=EN')
    api = json.loads(api_requests.content)
    return render(request,'home.html',{'api':api, 'price':price, 'coinprice':coinprice })

(Vitor Freitas) #2

Here is a simple example paginating by 10 news:

from django.shortcuts import render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
import requests, json

def home(request):
    api_requests = requests.get('https://min-api.cryptocompare.com/data/v2/news/?lang=EN')
    api = json.loads(api_requests.content)

    page = request.GET.get('page', 1)

    paginator = Paginator(api['Data'], 10)
    try:
        news_list = paginator.page(page)
    except PageNotAnInteger:
        news_list = paginator.page(1)
    except EmptyPage:
        news_list = paginator.page(paginator.num_pages)

    return render(request,'home.html', {
        'news_list': news_list
    })

If you want to change the number of news per page (let’s say 5):

paginator = Paginator(api['Data'], 5)

Then in your HTML template:

<!-- News display -->
{% for news in news_list %}
  <h3>{{ news.title }}</h3>
  <p>{{ news.body }}</p>
{% endfor %}

<!-- Paginator -->
<hr>
<div>
  {% for i in news_list.paginator.page_range %}
    {% if news_list.number == i %}
      <span>{{ i }}</span>
    {% else %}
      <a href="?page={{ i }}">{{ i }}</a>
    {% endif %}
  {% endfor %}
</div>

You can read more about how Paginator work here:


(Nehat Khan) #3

Hello sir, pagination doesn’t work, it only shows that pages number in the template but doesn’t grab the news list. Is there any other method to grab only 6 articles of news instead of garbing whole. paginatoer works fine with the model view but in my case its not showing anything.


(Vitor Freitas) #4

It works regardless of being a model. All it needs is an iterable.

Here is the code example that I created before posting:

Look carefully at home.html and views.py


(Nehat Khan) #5

It works now sir. Thanks a lot. Love you so much :blush: