Create News App in Django from Scratch

Django REST Framework is a robust and flexible toolkit for building Web APIs. It is written in python and allows the user to create some cool and awesome web applications. In this blog we will learn how to create a news app in Django from scratch. This will be another good project for you to show. Now coming back to our project we will be using news API for fetching news. Now before moving to our project let’s have a sneak peek to what is an API?

What is API?

Application Programming Interface abbreviated as API, is widely used nowadays. API basically provides an interface that allows multiple applications to communicate or share data with each other. When you use an application like Facebook to send an instant message or check weather using a weather forecasting application in your mobile phone, you are using an API.

Implementations

Step 1. Create Django Project

We are first going to create a django project, an app inside that project and then going to install newsapi-python, which will play a major role in our project.

  1. Create a Django project.

django-admin startproject blog_newsapi

  1. Create an app in that django-project.

python manage.py startapp blog14

  1. Install newsapi-python, newsapi helps you to fetch the news.

pip install newsapi-python

4. Add your app name in installed apps.

Settings.py

INSTALLED_APPS = [
    'blog14',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Step 2. Add files and Folder to the Django Project

We need to create a template folder in the django folder and a urls.py file in the app folder.

  1. Create a new folder in the django folder(here, blog_newsapi folder) save it with the name template.

2. Add the path for this template folder in blog_newsapi > settings.py .

Settings.py

import os
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

3. Create a new file in the app folder(here, blog14) save it with the name urls.py .

4. Add path for this url.py file in blog_newsapi > urls.py .

Urls.py

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('blog14.urls'))
]

Step3. Create News app

For creating news app we first have to get our own news api key, which we can get from the newsapi site you can find the link for the same in the steps given below:-

  1. Go to the News API site (https://newsapi.org/ ) and create an account.
  2. Copy the API KEY  provided.
Create News App in Django from Scratch

Or if you had an account you can just click on the button get API and you will get your API.

Create News App in Django from Scratch
Create News App in Django from Scratch

3. Create html file in template>index.html .

Index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- Optional theme -->
  </head>
  <body>
    <div class="jumbotron" style="color:black">
  
      <h1 style ="color:rgb(9, 7, 129)">
   Get The latest news on our website
      </h1>
  
    </div>
  
  
    <div class="container">
      {% for new, des, i in mylist %}
              
              <h1>Headline:</h1> {{ new }}
              {{ value|linebreaks }}
              <img src="{{ i }}" alt="">
              <h4>Article:</h4>{{ des }}
              {{ value|linebreaks }}
              <hr syle="width:10px;">
  
      {% endfor %}
    </div>
  
  </body>
</html>

4. Create a path for the index html page in blog14 > urls.py .

Urls.py

from django.urls import path,include
from . import views
urlpatterns = [
    path('',views.index,name='index')
]

5. Create a function for the index page in blog14 > views.py .

Views.py

from django.shortcuts import render
from newsapi import NewsApiClient
  
# Create your views here. 
def index(request):
      
    newsapi = NewsApiClient(api_key ='cadbc2508df2455eaac5c72e19d342c9')
    top = newsapi.get_top_headlines(sources ='techcrunch')
  
    l = top['articles']
    desc =[]
    news =[]
    img =[]
  
    for i in range(len(l)):
        f = l[i]
        news.append(f['title'])
        desc.append(f['description'])
        img.append(f['urlToImage'])
    mylist = zip(news, desc, img)
  
    return render(request, 'index.html', context ={"mylist":mylist})

Output:-

Output

Quick Revision

  1. Create your django project folder.
  2. Create an app folder in the django project folder.
  3. Install newsapi-python.
  4. Add template folder in the django folder and provide its path in django_folder > settings.py .
  5. Add file named as urls.py in the app folder and provide its path in django_project > urls.py.
  6. Get news api key.
  7. Add html code for the  in django_project > template > index.html.
  8. Create path for index html page in app_folder > urls.py.
  9.  Add function for the index html page in app_folder > views.py.

Github Link

https://github.com/jaya2320/newsapp-blog

Conclusion

So, we had learned how to create a news app in Django. I hope this blog will be useful for you and helps you to understand each and every step. Hope all your doubts get cleared. Thank you.