DEV Community

Cover image for Consuming API with Django and Chart.js [Part 1]
Faruq Abdulsalam
Faruq Abdulsalam

Posted on • Edited on

Consuming API with Django and Chart.js [Part 1]

This is going to be a 3-part series tutorial, you are going to learn how to consume an API in Django and present it in graphical format using Chart.js. We will be making use of CoinDesk’s Api “Historical BPI Data of bitcoin”. Here is a sample of an API we'll be making use of.

PART 1

Setup

If you already know how to do this, you can skim through part 1 then move to the next part of the series.

I’ll assume that you already have python installed on your machine. If you don't, you can download and set it up via this link. Please ensure you download the latest version of python. (Python 3.97)

Open the Command Line on Windows, Terminal on Mac, and Linux and navigate to the directory where you want to store the project and create a new directory

mkdir bitcoin_api
Enter fullscreen mode Exit fullscreen mode

Move into the new directory

cd bitcoin_api
Enter fullscreen mode Exit fullscreen mode

Create a Virtual environment.

It is recommended to always create a virtual environment before you start your project. This helps you to separate the packages you use in this application from other applications; any change you make here wont affect the same package in another application on your system. To create a virtual environment on your system; run this command:

For mac/unix users: python3 -m venv env
For windows users: py -m venv env
Enter fullscreen mode Exit fullscreen mode

After creating the environment, activate it by running :

For mac/unix users: source env/bin/activate
For windows users: .\env\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

You can deactivate it by simply running the command below, but you don't have to deactivate it yet.

deactivate
Enter fullscreen mode Exit fullscreen mode

Installing Django

Now let us proceed to installing Django,

pip install django
Enter fullscreen mode Exit fullscreen mode

We are officially done with setting up our system for the Django project 🤝, now let us proceed to the project setup itself.

You thought we were done, aye? 😅. Don't worry we have just a few steps to go 😀 and then we'll proceed to code.
relax

Setting up the project

Create a new django project and name it “bitcoin-price”

django-admin startproject bitcoin_price
Enter fullscreen mode Exit fullscreen mode

Move into the project folder

cd bitcoin_price
Enter fullscreen mode Exit fullscreen mode

Create a new application named “price”

python manage.py startapp price
Enter fullscreen mode Exit fullscreen mode

Next, we have to add the name of the newly created app to the settings.py file in our project directory “bitcoin-price”. Open the settings.py file; under the “installed apps” setting add the string “price” to it so it ends up looking like this.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #my_app
    'price',
]
Enter fullscreen mode Exit fullscreen mode

Next, we’ll add our HTML template and also static files paths to the settings which will handle the HTML, CSS and javascript files.
We will only be changing the content of 'DIRS' here. All we are doing is declaring the path to the folder where we will store the HTML templates

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [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',
            ],
        },
    },
]
Enter fullscreen mode Exit fullscreen mode

At the bottom of our settings file, you'll see the static files section. Add this under the STATIC_URL configuration

STATICFILES_DIRS = [
    BASE_DIR/ 'static'
]

Enter fullscreen mode Exit fullscreen mode

Your static file configuration should now look like this.

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR/ 'static'
]

Enter fullscreen mode Exit fullscreen mode

That’s all we need to do under the settings.py file.

We won't be needing a database for this tutorial as the API data will be fetched and rendered in real-time. So you can go ahead and delete the models.py file under your app “price”. Yes, you read that right, we won't be needing the 'models.py' file😅. Trust me on this one😁. At the moment, your folder structure should be looking like this 👇
folder structure

Now migrate your “changes” with this command

python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Then you can start your server to ensure that everything is working properly

python manage.py runserver 
Enter fullscreen mode Exit fullscreen mode

Copy this URL: http://127.0.0.1:8000 and open it in any browser of your choice. You should be able to see something similar to this 👇
Django default page
Next, we’ll be creating the static and template folders. ENSURE you are in the folder that contains the manage.py file

Create the static folder and in it, two extra folders named CSS and JS respectively. They’ll hold our javascript and styling codes later on.

Then create a folder named “templates”. Create a base.html file in it. Then paste the following code in the html file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Bitcoin Price Chart</title>
  </head>
  <body>

    <h1> CoinDesk's Bitcoin Api Data </h1>

  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now we need to configure our URL so we can view our HTML page. Open urls.py file in the bitcoin_price folder. We need to import the include function and link the URL to our "price" application. We will set it up like this👇.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("price.urls"))
]
Enter fullscreen mode Exit fullscreen mode

It is similar to what we have, but we just need to edit line 2 and add line 5.
Next, we open the price folder and create a new file with the name urls.py. Copy this into the new file.

from django.urls import path
from .views import chart

urlpatterns = [
    path("", chart, name="chart"),
]
Enter fullscreen mode Exit fullscreen mode

We'll be creating the chart function we are importing into our URL shortly. Sorry for bringing it in before creating it.

Views.py

Here is where we'll place the heart of our project. For now, we'll just add a small function, so we can confirm that we can view our HTML files properly. Here is the code we'll be adding to our views.py file.

def chart(request):
     context = {}
     return render(request, 'base.html', context)
Enter fullscreen mode Exit fullscreen mode

When we try to access our URL from the browser, the chart function gets called and it renders our base page. Ignore the context dictionary for now. It is for future use😉.

You might see this error in your command line or terminal: "ModuleNotFoundError: No module named 'price.urls' " .This is because our server was still running when we made the changes so it cannot read the urls.py file we just created. Shut down the server with

 'Control + C' buttons on your keyboard
Enter fullscreen mode Exit fullscreen mode

and restart the server to ensure that everything is working properly

python manage.py runserver 
Enter fullscreen mode Exit fullscreen mode

Refresh the page you opened on your server. You should see the h1 content in our base.html file on the page.
Default page

(If you are not seeing anything. Two things might have happened:

  1. You closed the page. Open this URL: 127.0.0.1:8000 in your browser
  2. You already took down the server. Run the command below.
python manage.py runserver
then open this URL 127.0.0.1:8000 in your browser.
Enter fullscreen mode Exit fullscreen mode

You should now be able to see the page above👆.

Finally we create a template folder in our price directory and add a chart.html file to it.

Voilà!!! We have successfully finished setting up our Django project. Your project file structure should look like this now.
New FolderStructure

Now let’s get started with writing the logic codes ✍️. No, we won't be doing that in Part 1 😅. Let's get some rest and push the major work to the next part of the series. If you are the strong one 💪, you can proceed straight away to Part 2 May the force be with you

If you have any questions, feel free to drop them as a comment or send me a message on Linkedin or Twitter and I'll ensure I respond as quickly as I can. Ciao 👋

Top comments (1)

Collapse
 
meysam1365tehrani profile image
Meysam1365tehrani

hello my friend
I make Django App according your tutorial but I receive message:
"TemplateDoesNotExist at /
chart.html"
please help me for debug this error .