django

Creating Simple Web App Using Django

Build a small Django web app that pulls bitcoin news from a news API and renders the articles with a template: project setup, app, views, and URL routing.

This post walks through building a simple web app with the Django web framework.

What is Django?

Django is a web framework for building web apps quickly, without reinventing everything from scratch. It uses the MVC architecture: Model, View, and Controller. Model deals with data, View deals with web logic, and Controller is the URL dispatcher. Django also uses an ORM (Object Relational Mapping), which lets you work with application data from a relational database.

A Django app is a model for data, a view for logic, and a URL that connects them to a template.

Getting started with Django

  • Make sure python and pip are installed.

  • With python and pip ready, install pipenv, which manages project dependencies. See the Pipenv docs for install instructions.

  • With pipenv installed, create a project folder for Django. To install django, first activate the virtual environment with pipenv shell, then run pipenv install django.

  • Django is now installed.

Starting the project

With Django installed, start the first project. This one is named newsapp. Running django-admin.py startproject newsapp generates a folder with several files.

Files created by django-admin startproject newsapp

  • __init__.py tells the Python interpreter that this directory is a package.
  • setting.py holds the project’s settings, including the list of apps and middleware used by the Django project.
  • urls.py holds the project-level URL information and connects the apps to the project.
  • wsgi.py matters if you want to deploy to an Apache server, since Django is Python-based and Python uses a wsgi server.
  • manage.py usually lives outside the project directory and provides commands like runserver, makemigrations, and migrate.

Run the server with python manage.py runserver and view it at http://127.0.0.1:8000/.

Performing system checks...

System check identified no issues (0 silenced).

You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

November 07, 2019 - 16:30:33
Django version 2.2.6, using settings 'newsapp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Note: Don’t worry about the unapplied migrations.

Creating a Django app

Difference between a project and an app

In simple terms, an app does one thing, like a social media network, a blog, or a news app. A project is the collection of configurations and apps for a particular website.

Creating the app

With the Django project created, create the financial news app by running python manage.py startapp financialnewsapp.

Files inside the new financialnews app

Before the next step, here’s an overview of each file in the app just created.

  • admin.py is a configuration file for the built-in Django admin.
  • apps.py is the configuration file for the app.
  • tests.py is where you write unit tests for the app.
  • views.py handles requests and responses.
  • models.py is where you define data with Python classes, which the ORM turns into database tables.
  • migrations/ tracks every database migration you make.

Before the next step, add the newly created app to SETTINGS.PY in the newsapp/ project.

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

As you can see, it already has some pre-installed apps. These offer prebuilt solutions for things like authentication and staticfiles.

Writing the view

Now write the view that queries the top 10 bitcoin news articles and displays them on an HTML page. First, install newsapi and get an API key. Install newsapi with pipenv install newsapi-python. Before you can access the API, you need a key.

With newsapi installed, write the view that requests news articles and displays them on the HTML page.

Add the following to views.py.

python
from django.shortcuts import render
from django.shortcuts import render
from newsapi import NewsApiClient
import json
# Initializing API KEY
newsapi = NewsApiClient(api_key='xxxxxxx')
all_articles = newsapi.get_everything(q='bitcoin',sources='yahoo,the-verge,cnbc,bloomberg',
language='en',sort_by='relevancy')

# loading all_articles as json
new = json.dumps(all_articles)
# This will allow us to create creat dictionary from the json which will make easier for us to use the data
data = json.loads(new)
def index(request):
    return render(request,'news/index.html',{'data':data})

With the view’s logic in place, create a url that requests it. First, add the app’s URLs to the project’s urls.py file.

python
"""newsapp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path ,include

urlpatterns = [
    path('admin/', admin.site.urls),
    # This line will look for urls in app
    path('',include('financialnewsapp.urls'))
]

Now create a new urls.py file in the financialnewsapp/ folder and add the following.

python
from django.urls import path
# Import our views
from . import views
# When we request home/index url it use index view logic
urlpatterns = [
    path('',views.index,name='index')
    ]

Lastly, create a templates/ folder inside the app directory, where Django looks for HTML files.

Inside templates/, create another folder to hold the HTML file, something like templates/news/index.html.

After creating the directory and file, paste the following code into it.

html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CryptoCurrency News</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css">
    <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
</head>
<body>
<section class="hero is-medium is-primary is-bold">
  <div class="hero-body">
    <div class="container">
      <h1 class="title">
        CryptoCurrency News
      </h1>
      <h2 class="subtitle">
        Bitcoin News From Major News Sources
      </h2>
    </div>
  </div>
</section>
<div class="container">
<div class=columns>
<div class="column">
<div class="box">
		{% for key in data.articles%}
  <article class="media">
    <div class="media-left">
      <figure class="image is-64x64">
        <img src="{{key.urlToImage}}" alt="Image">
      </figure>
    </div>
    <div class="media-content">
      <div class="content">
        <p>
          <strong>{{key.author}}</strong> <small>@{{key.source.name}}</small> <small>{{key.publishedAt}}</small>
          <br>
         {{key.title}}
         <br>
         <a href="{{key.url}}">{{key.url}}</a>
         <br>
         {{key.description}}
        </p>
      </div>
    </div>
  </article>
		{%endfor%}

</div>
</div>
</div>
</div>
</body>
</html>

This uses Bulma to keep it clean. As you can see, Django uses the Jinja templating engine to render dynamic data from a database or API.

The template loops through the articles and accesses each dictionary key’s value with the double curly brace tags.

Note:

  • Single curly braces are used for conditions, for loops, or extending a template in the Jinja templating engine.
  • Double curly braces evaluate something, in this case the value of each key.

That’s a simple django app that displays bitcoin news. If I missed anything, feel free to DM me on Twitter.

End result

The finished app: a CryptoCurrency News page listing Bitcoin headlines