How I Created a Calculator App Using Django โ€“ Part 3

5/5 - (1 vote)

We have finished designing the calculator app. Using a hypertext markup language (HTML), we set the structure of the calculator. The Cascading Style Sheet (CSS) was used to beautify the calculator and to design the layout. Finally, we used JavaScript to make the app interact with other buttons and perform basic calculations.

Our task is done but there is a problem. Throughout the development stage, we used a text editor to write our code and to observe what we were doing on a browser, we copied the path to the file and pasted it to the address bar.

Without doing this, we cannot see the calculator app.

Furthermore, if we were to call it a day, how then will we include Python language as part of learning Python through building projects? Just as we mentioned in the first part of this project tutorial, we will use Django, a Python framework, to host this app.

Django Setup

We have a lot to do on the terminal to set up Django. We start by creating a separate folder for this project, activating a virtual environment and installing Django.

mkdir project && cd project
python3 -m venv .venv
source .venv/bin/activate
pip install django tzdata

Next, we start Django project and Django app.

django-admin startproject operation .
python3 manage.py startapp calculator

At this stage, you are expected to have these files in your folder:

README.md  calculator  index.html  manage.py  operation  script.js  styles.css

Next, we create templates and static folders. Inside the static folder, we create two additional folders for JavaScript and CSS.

mkdir -p templates static/js static/css

Making changes in the settings file

We now head over to the settings.py file to inform Django of what we have done. Inside the file, start by adding the newly created app in the INSTALLED_APPS section.

INSTALLED_APPS = [
    โ€ฆ
    # custom app
    'calculator',
]

Next, import the os module and go to the TEMPLATES section to make this one-line change.

TEMPLATES = [
โ€ฆ
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
โ€ฆ
]

We have static files. To tell Django where to look for these static files, go to the bottom of the file just below the STATIC_URL, and also make this one-line change.

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

Next, in your project-level URL, make this change:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('calculator.urls')),
]

On the terminal, rename the CSS file and move the template and static files to their rightful place.

mv styles.css base.css
mv index.html templates

mv base.css static/css/

mv script.js static/js/

This is how your project folder is expected to be:

README.md  calculator  manage.py  operation  static  templates

Making changes to the Markup file

Next, open your index.html. Load the static files at the top like this:

{% load static %}

Adjust the link that points to the CSS file to be like this:

    <link rel="stylesheet" href="{% static 'css/base.css' %}">

The script tag for the JavaScript will also be like this:

<script src="{% static 'js/script.js' %}โ€></script>

The view function and the app-level URL

To view the calculator app on the local server, we have to create a view function and render it.

The view function is quite simple:

from django.shortcuts import render

def index(request):
    return render(request, 'index.html')

For the app-level URL, create a urls.py file inside the app folder.

from django.urls import path
from .views import index


urlpatterns = [
    path('', index, name='home'),
]

Thatโ€™s all. We can now start the local server.

python3 manage.py migrate
python3 manage.py runserver

A little addition

Letโ€™s extend this calculator app to include a digital clock so that as we are performing calculations, we can be observing the time as well. Add this to the index.html file just after the <body> tag:

{% block top %} {% include 'clock.html' %} {% endblock top %}

I want to adhere to the principle of separation of concern. Hence, we will create a separate file for the clock and include it in the index.html file. Note the block keyword: top. It can be any word of your choice. I use it to indicate that I want the clock to appear at the top of the calculator.

Everything is going to be on a separate file. So, since we are still in the index.html file, include the link to the CSS and JavaScript files.

<link rel="stylesheet" href="{% static 'css/clock.css' %}">
<script src="{% static 'js/clock.js' %}"></script>

Now, create a clock.html file inside the templates folder.

{% block top %}

<div id="MyClockDisplay" class="clock"></div>

{% endblock top %}

Thatโ€™s all the markup we need. The rest will be done with JavaScript. Notice how we make sure this markup appears in the index.html file by wrapping the code inside the block statements.

Next is the CSS file. It will go inside the css folder.

.clock {
  position: absolute;
  top: 10%;
  left: 45%;
  transform: translateX(-50%) translateY(-50%);
  color: #17d4fe;
  font-size: 60px;
  font-family: Times New Roman;
  letter-spacing: 7px;
}

We have explained some of these in the first part series of this project article. We use the class clock to style the HTML element. The absolute position positions the element to its nearest ancestor. Otherwise, it positions the element to its initial block.

I use the top and left properties (10% away from the top edge and 45% away from the left edge) to make sure the digital clock rest on top of the calculator. The transform property also makes sure the element is centered horizontally and vertically.

Next is JavaScript. This will display the clock and make it tick.

window.onload = function showTime(){
  let date = new Date(),
      h = date.getHours(),
      m = date.getMinutes(),
      s = date.getSeconds(),
      session = 'AM';

  if (h == 0){
    h = 12;
  }

  if (h > 12){
    h -=  12;
    session = 'PM';
  }

  h = (h < 10) ? '0' + h : h;
  m = (m < 10) ? '0' + m : m;
  s = (s < 10) ? '0' + s : s;

  let time = h + ':' + m + ':' + s + ' ' + session;

  document.getElementById('MyClockDisplay').innerHTML = time;

  setTimeout(showTime, 1000);
}

showTime();

The window.onload makes sure that the page is loaded before any JavaScript code is run. Inside the showTime() function, we create a date object and using its get methods assign the seconds, minutes and hours in local time to a variable.

If the hour is equal to 0 (i.e., midnight), it is set to 12 to avoid the use of 24-hour time. If the hour is greater than 12 (i.e., in the afternoon), 12 is subtracted from it and the value of session initially set to โ€˜AMโ€™ is set to ‘PM’.

The function then checks if the hours, minutes, and seconds are less than 10. If they are, a ‘0’ is added before them to ensure that they always have two digits. It then formats the time and stores it in a variable, time.

Using the .innerHTML of the element, we display the current time on the page. Finally, the function calls itself every 1 second to update the time.

Conclusion

This is the end of this project tutorial on creating a calculator app. The project focuses on how to use JavaScript to interact with the DOM. As an extension, we demonstrated how to add a digital clock to be displayed on the calculator app.

No doubt, you have learned a lot from this project tutorial. Use this knowledge to create your project using the Django framework. Be sure to check the source code on my GitHub page. You are welcome!