05-16-2023, 12:37 PM
How I Designed a News Aggregator Web Application Using Django
<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{"align":"left","id":"1362488","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"0","legendonly":"","readonly":"","score":"0","starsonly":"","best":"5","gap":"5","greet":"Rate this post","legend":"0\/5 - (0 votes)","size":"24","title":"How I Designed a News Aggregator Web Application Using Django","width":"0","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> <span class="kksr-muted">Rate this post</span> </div>
</p></div>
<p>A news aggregator is simply a web application that aggregates or collects news articles from different websites and presents them in a single location so that users can visit the location (website) and click on the link to read news of interest. This saves time and resources.</p>
<p>In this project article, we will learn how to design a news aggregator web application using the Django framework. Specifically, we will scrape the web for news articles using a Python module, and have them displayed on our Django web application.</p>
<p>This is something similar to the News App designed using the Flask framework in previous tutorial projects.</p>
<h2 class="wp-block-heading">Setting up Django</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="917" height="607" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-207.png" alt="" class="wp-image-1362638" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-207.png 917w, https://blog.finxter.com/wp-content/uplo...00x199.png 300w, https://blog.finxter.com/wp-content/uplo...68x508.png 768w" sizes="(max-width: 917px) 100vw, 917px" /></figure>
</div>
<p>Follow these steps to set up Django in your Ubuntu terminal:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ mkdir project
$ cd project
$ python3 -m venv .venv
$ source .venv/bin/activate
(.venv) $ pip install django requests bs4
(.venv) $ django-admin startproject newsAggregator .
(.venv) $ python3 manage.py startapp news
(.venv) $ python3 manage.py migrate
(.venv) $ python3 manage.py runserver
</pre>
<p>Remember, the Django project is created in the project folder as indicated by the dot command. Run the local server to confirm that the installation went successfully.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-204.png" alt="" class="wp-image-1362544" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-204.png 720w, https://blog.finxter.com/wp-content/uplo...00x169.png 300w" sizes="(max-width: 720px) 100vw, 720px" /></figure>
</div>
<h2 class="wp-block-heading">Creating Views</h2>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from django.shortcuts import render
import requests from decouple import config API_KEY = config('NEWS_API_KEY') COUNTRY = 'us' def news_lists(request): if request.method == 'POST': url = f'https://newsapi.org/v2/top-headlines?country={COUNTRY}&apiKey={API_KEY}' res = requests.get(url).json() news_articles = res['articles'] context = { 'news_articles': news_articles } return render(request, 'home.html', context) return render(request, 'home.html'
</pre>
<p>We import the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" data-type="post" data-id="37837" target="_blank">requests</a></code> module which is an essential tool for retrieving data from a webpage. We use the Python-decouple module to load environment variables. The first variable is the News API key. If you have read the <a href="https://blog.finxter.com/how-i-created-a-news-application-using-the-flask-framework/" data-type="post" data-id="1330088" target="_blank" rel="noreferrer noopener">project tutorial</a> where I used the Flask framework to create a similar project, you are expected to have your API key.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="922" height="615" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-206.png" alt="" class="wp-image-1362635" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-206.png 922w, https://blog.finxter.com/wp-content/uplo...00x200.png 300w, https://blog.finxter.com/wp-content/uplo...68x512.png 768w" sizes="(max-width: 922px) 100vw, 922px" /></figure>
</div>
<p>Create a <code>.env</code> file to save your environment variables. Inside the file, write this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">API_KEY = 'Your API key'
DJANGO_SECRET_KEY = 'Secret Key'</pre>
<p>The Second environment variable is Django’s secret key found in the <code>settings.py</code> file. The instruction from Django is to keep the secret key secret. </p>
<p>Of course, this applies to deploying an app to a production server. But since I will be pushing the files to <a href="https://github.com/finxter/Django_News_App" data-type="URL" data-id="https://github.com/finxter/Django_News_App" target="_blank" rel="noreferrer noopener">GitHub</a>,<sup> </sup>I have to follow best practices by keeping it secret and loading it as an environment variable.</p>
<p>Another Python module, Python-dotenv is working behind the scene to make all these possible. If you start the server without installing the module, you may get an error message from Django.</p>
<p>Back to the view function, if the request method is POST, we use the requests module to fetch current news from a defined country. You can change it to use any country of your choice. We then save the response in a <a href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank" rel="noreferrer noopener">dictionary</a> form and render it to the <code>home.html</code> webpage.</p>
<h2 class="wp-block-heading">Creating Templates</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="921" height="550" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-208.png" alt="" class="wp-image-1362639" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-208.png 921w, https://blog.finxter.com/wp-content/uplo...00x179.png 300w, https://blog.finxter.com/wp-content/uplo...68x459.png 768w" sizes="(max-width: 921px) 100vw, 921px" /></figure>
</div>
<p>We will create a <code>home.html</code> file inside a templates folder. So, create the folder and the file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""><!DOCTYPE html>
<html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" /> <title>Django News Headline</title> </head> <body> <h1 class="text-center mt-4 mb-5">Django News Headlines</h1> <div class="row mt-5"> <div class="col-md-2"></div> <div class="col-md-8"> <div class="row"> {% for news in news_articles %} <div class="col-md-4 mb-5"> <div class="card" style="width: 18rem"> <img src="{{ news.urlToImage }}" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">{{ news.title }}</h5> <p class="card-text">{{ news.description }}</p> <a href="{{ news.url }}" class="btn btn-primary">Read More</a> </div> </div> </div> {% endfor %} </div> </div> <div class="col-md-2"></div> </div> <!-- Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous" ></script> </body>
</html>
</pre>
<p>Going back to the view function, you will notice the variable <code>news_articles</code>. </p>
<p>When the response was converted to JSON, the news content was found in <code>res['articles']</code>. Having stored it in the news_articles, we simply use Django’s <code>for</code>-loop to iterate through the articles. This is also similar to what we did using the <a href="https://blog.finxter.com/how-i-created-a-news-application-using-the-flask-framework/" data-type="post" data-id="1330088" target="_blank" rel="noreferrer noopener">Flask framework</a>.</p>
<p>Each iteration displays the news title, image, description, and a link to read more</p>
<h2 class="wp-block-heading">Registering Apps and URLs</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="917" height="617" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-209.png" alt="" class="wp-image-1362640" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-209.png 917w, https://blog.finxter.com/wp-content/uplo...00x202.png 300w, https://blog.finxter.com/wp-content/uplo...68x517.png 768w" sizes="(max-width: 917px) 100vw, 917px" /></figure>
</div>
<p>Go to the <code>settings.py</code> file. If you will be pushing your code to GitHub, remove the Django secret key, store it in the <code>.env</code> file, and load it using the <code>Python-decouple</code> module.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from pathlib import Path
import os
from decouple import config SECRET_KEY = config('DJANGO_SECRET_KEY') # Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/ho...checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = SECRET_KEY
</pre>
<p>Scroll down to the <code>INSTALLED_APPS</code> section, and register the news app.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news',
]
</pre>
<p>Scroll down to the TEMPLATES section, and also let Django know of an existing templates folder.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], #add these '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', ], }, },
]
</pre>
<p>Next is the URLs. Go to the project-level <code>urls.py</code> file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from django.contrib import admin
from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('news.urls')),
]
</pre>
<p>This also informs Django of an existing app-level URLs. Finally, let’s create the app-level <code>urls.py</code> file. This time, inside the news folder.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from django.urls import path
from .views import news_lists urlpatterns = [ path('', news_lists, name='home'),
]
</pre>
<p>The <code>news_lists()</code> is our view function. The URL will be referred to as home in templates files where necessary.</p>
<p>Everything is done and dusted. Let’s start the local server. Run <code>python3 manage.py runserver</code><em> </em>in your terminal.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-205.png" alt="" class="wp-image-1362562" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-205.png 720w, https://blog.finxter.com/wp-content/uplo...00x169.png 300w" sizes="(max-width: 720px) 100vw, 720px" /></figure>
</div>
<h2 class="wp-block-heading">Conclusion</h2>
<p>Having gone through this project, no doubt, you will appreciate the simplicity Flask has compared with Django. </p>
<p>However, Django can be used to create web apps far more complex than the Flask framework. What we just did with Django is for learning’s sake, to improve our Python skills. You have learned a thing or two. </p>
<p>Use that knowledge to create a similar app and share it with the world!</p>
<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-i-created-a-news-application-using-the-flask-framework/" data-type="post" data-id="1330088" target="_blank" rel="noreferrer noopener">How I created a News Application using the Flask Framework</a></p>
</div>
https://www.sickgaming.net/blog/2023/05/...ng-django/
<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{"align":"left","id":"1362488","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"0","legendonly":"","readonly":"","score":"0","starsonly":"","best":"5","gap":"5","greet":"Rate this post","legend":"0\/5 - (0 votes)","size":"24","title":"How I Designed a News Aggregator Web Application Using Django","width":"0","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> <span class="kksr-muted">Rate this post</span> </div>
</p></div>
<p>A news aggregator is simply a web application that aggregates or collects news articles from different websites and presents them in a single location so that users can visit the location (website) and click on the link to read news of interest. This saves time and resources.</p>
<p>In this project article, we will learn how to design a news aggregator web application using the Django framework. Specifically, we will scrape the web for news articles using a Python module, and have them displayed on our Django web application.</p>
<p>This is something similar to the News App designed using the Flask framework in previous tutorial projects.</p>
<h2 class="wp-block-heading">Setting up Django</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="917" height="607" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-207.png" alt="" class="wp-image-1362638" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-207.png 917w, https://blog.finxter.com/wp-content/uplo...00x199.png 300w, https://blog.finxter.com/wp-content/uplo...68x508.png 768w" sizes="(max-width: 917px) 100vw, 917px" /></figure>
</div>
<p>Follow these steps to set up Django in your Ubuntu terminal:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ mkdir project
$ cd project
$ python3 -m venv .venv
$ source .venv/bin/activate
(.venv) $ pip install django requests bs4
(.venv) $ django-admin startproject newsAggregator .
(.venv) $ python3 manage.py startapp news
(.venv) $ python3 manage.py migrate
(.venv) $ python3 manage.py runserver
</pre>
<p>Remember, the Django project is created in the project folder as indicated by the dot command. Run the local server to confirm that the installation went successfully.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-204.png" alt="" class="wp-image-1362544" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-204.png 720w, https://blog.finxter.com/wp-content/uplo...00x169.png 300w" sizes="(max-width: 720px) 100vw, 720px" /></figure>
</div>
<h2 class="wp-block-heading">Creating Views</h2>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from django.shortcuts import render
import requests from decouple import config API_KEY = config('NEWS_API_KEY') COUNTRY = 'us' def news_lists(request): if request.method == 'POST': url = f'https://newsapi.org/v2/top-headlines?country={COUNTRY}&apiKey={API_KEY}' res = requests.get(url).json() news_articles = res['articles'] context = { 'news_articles': news_articles } return render(request, 'home.html', context) return render(request, 'home.html'
</pre>
<p>We import the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" data-type="post" data-id="37837" target="_blank">requests</a></code> module which is an essential tool for retrieving data from a webpage. We use the Python-decouple module to load environment variables. The first variable is the News API key. If you have read the <a href="https://blog.finxter.com/how-i-created-a-news-application-using-the-flask-framework/" data-type="post" data-id="1330088" target="_blank" rel="noreferrer noopener">project tutorial</a> where I used the Flask framework to create a similar project, you are expected to have your API key.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="922" height="615" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-206.png" alt="" class="wp-image-1362635" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-206.png 922w, https://blog.finxter.com/wp-content/uplo...00x200.png 300w, https://blog.finxter.com/wp-content/uplo...68x512.png 768w" sizes="(max-width: 922px) 100vw, 922px" /></figure>
</div>
<p>Create a <code>.env</code> file to save your environment variables. Inside the file, write this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">API_KEY = 'Your API key'
DJANGO_SECRET_KEY = 'Secret Key'</pre>
<p>The Second environment variable is Django’s secret key found in the <code>settings.py</code> file. The instruction from Django is to keep the secret key secret. </p>
<p>Of course, this applies to deploying an app to a production server. But since I will be pushing the files to <a href="https://github.com/finxter/Django_News_App" data-type="URL" data-id="https://github.com/finxter/Django_News_App" target="_blank" rel="noreferrer noopener">GitHub</a>,<sup> </sup>I have to follow best practices by keeping it secret and loading it as an environment variable.</p>
<p>Another Python module, Python-dotenv is working behind the scene to make all these possible. If you start the server without installing the module, you may get an error message from Django.</p>
<p>Back to the view function, if the request method is POST, we use the requests module to fetch current news from a defined country. You can change it to use any country of your choice. We then save the response in a <a href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank" rel="noreferrer noopener">dictionary</a> form and render it to the <code>home.html</code> webpage.</p>
<h2 class="wp-block-heading">Creating Templates</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="921" height="550" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-208.png" alt="" class="wp-image-1362639" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-208.png 921w, https://blog.finxter.com/wp-content/uplo...00x179.png 300w, https://blog.finxter.com/wp-content/uplo...68x459.png 768w" sizes="(max-width: 921px) 100vw, 921px" /></figure>
</div>
<p>We will create a <code>home.html</code> file inside a templates folder. So, create the folder and the file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""><!DOCTYPE html>
<html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" /> <title>Django News Headline</title> </head> <body> <h1 class="text-center mt-4 mb-5">Django News Headlines</h1> <div class="row mt-5"> <div class="col-md-2"></div> <div class="col-md-8"> <div class="row"> {% for news in news_articles %} <div class="col-md-4 mb-5"> <div class="card" style="width: 18rem"> <img src="{{ news.urlToImage }}" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">{{ news.title }}</h5> <p class="card-text">{{ news.description }}</p> <a href="{{ news.url }}" class="btn btn-primary">Read More</a> </div> </div> </div> {% endfor %} </div> </div> <div class="col-md-2"></div> </div> <!-- Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous" ></script> </body>
</html>
</pre>
<p>Going back to the view function, you will notice the variable <code>news_articles</code>. </p>
<p>When the response was converted to JSON, the news content was found in <code>res['articles']</code>. Having stored it in the news_articles, we simply use Django’s <code>for</code>-loop to iterate through the articles. This is also similar to what we did using the <a href="https://blog.finxter.com/how-i-created-a-news-application-using-the-flask-framework/" data-type="post" data-id="1330088" target="_blank" rel="noreferrer noopener">Flask framework</a>.</p>
<p>Each iteration displays the news title, image, description, and a link to read more</p>
<h2 class="wp-block-heading">Registering Apps and URLs</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="917" height="617" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-209.png" alt="" class="wp-image-1362640" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-209.png 917w, https://blog.finxter.com/wp-content/uplo...00x202.png 300w, https://blog.finxter.com/wp-content/uplo...68x517.png 768w" sizes="(max-width: 917px) 100vw, 917px" /></figure>
</div>
<p>Go to the <code>settings.py</code> file. If you will be pushing your code to GitHub, remove the Django secret key, store it in the <code>.env</code> file, and load it using the <code>Python-decouple</code> module.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from pathlib import Path
import os
from decouple import config SECRET_KEY = config('DJANGO_SECRET_KEY') # Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/ho...checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = SECRET_KEY
</pre>
<p>Scroll down to the <code>INSTALLED_APPS</code> section, and register the news app.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news',
]
</pre>
<p>Scroll down to the TEMPLATES section, and also let Django know of an existing templates folder.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], #add these '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', ], }, },
]
</pre>
<p>Next is the URLs. Go to the project-level <code>urls.py</code> file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from django.contrib import admin
from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('news.urls')),
]
</pre>
<p>This also informs Django of an existing app-level URLs. Finally, let’s create the app-level <code>urls.py</code> file. This time, inside the news folder.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from django.urls import path
from .views import news_lists urlpatterns = [ path('', news_lists, name='home'),
]
</pre>
<p>The <code>news_lists()</code> is our view function. The URL will be referred to as home in templates files where necessary.</p>
<p>Everything is done and dusted. Let’s start the local server. Run <code>python3 manage.py runserver</code><em> </em>in your terminal.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-205.png" alt="" class="wp-image-1362562" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-205.png 720w, https://blog.finxter.com/wp-content/uplo...00x169.png 300w" sizes="(max-width: 720px) 100vw, 720px" /></figure>
</div>
<h2 class="wp-block-heading">Conclusion</h2>
<p>Having gone through this project, no doubt, you will appreciate the simplicity Flask has compared with Django. </p>
<p>However, Django can be used to create web apps far more complex than the Flask framework. What we just did with Django is for learning’s sake, to improve our Python skills. You have learned a thing or two. </p>
<p>Use that knowledge to create a similar app and share it with the world!</p>
<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-i-created-a-news-application-using-the-flask-framework/" data-type="post" data-id="1330088" target="_blank" rel="noreferrer noopener">How I created a News Application using the Flask Framework</a></p>
</div>
https://www.sickgaming.net/blog/2023/05/...ng-django/