Author Archives: Dan Dumitrache

About Dan Dumitrache

Dan is a web developer based in Ireland and this is his WordPress blog.

Python testing with unittest module | Testing mathematical operations

The unittest module is part of Python’s standard library and it is very popular when it comes to testing Python code. You need two files (preferably placed in the same directory), one file that contains the code that is tested and another file with the code that tests the code of the first file.

My first file is named math_operators.py and it contains basic functions I am going to test. The second file is named test_math_operators.py and it is going to contain the testing code.

Note:
I am referring to this documentation when writing the tests on this page: https://docs.python.org/3/library/unittest.html#unittest.TestCase.debug.

Testing Python’s mathematical operators with unittest module

In order to start testing I have created the following basic functions in my math_operators.py file.

def addition(a, b):
	return a + b

def subtraction(a, b):
	return a - b

def multiplication(a, b):
	return a * b

def division(a, b):
	if b == 0:
		raise ValueError("Can't divide by zero!")
	return a / b

Continue reading

Building a To Do Application in Python using Django Framework – Part 06

In this 6th part all I want to do is to display the todo items, that I created through the admin panel, on the web page. It turns out to be actually very easy.

First of all we have to modify the view.py file, particularly the get_index() function. This is how my function looks like now:

from django.shortcuts import render
from .models import TodoItem

def get_todo_index(request):
    items = TodoItem.objects.all()
    return render(request, "todo/index.html", {'items': items})
    
def edit_todo_item(request, id):
    return render(request, "todo/edit.html")
    
def delete_todo_item(request, id):
    return render(request, "todo/delete.html")
    
def toggle_todo_item(request, id):
    return render(request, "todo/toggle.html")

Continue reading

Building a To Do Application in Python using Django Framework – Part 05

In this 5th part we are going to create an HTML template which will be our template for all other HTML pages.

In the home’s template folder (same folder as index.html) create a file named base.html and add the following code into it:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Todo App</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="{% static 'home/style.css' %}" type="text/css" />
    
    <script defer src="https://use.fontawesome.com/releases/v5.0.8/js/solid.js" integrity="sha384-+Ga2s7YBbhOD6nie0DzrZpJes+b2K1xkpKxTFFcx59QmVPaSA8c7pycsNaFwUK6l" crossorigin="anonymous"></script>
    <script defer src="https://use.fontawesome.com/releases/v5.0.8/js/fontawesome.js" integrity="sha384-7ox8Q2yzO/uWircfojVuCQOZl+ZZBg2D2J5nkpLqzH1HY0C1dHlTKIbpRz/LG23c" crossorigin="anonymous"></script>
    
</head>
<body>
    
    <div class="container-fluid">
        <header class="row bg-dark pl-5 pr-5">
            <div class="col-md-6 p-2">
                <h1 id="title" class="navbar-text text-light border border-light rounded-circle p-3">ToDo</h1>
            </div>
            <nav class="col-md-6 text-right pt-4">
                <a href="{% url 'home' %}"><i class="fas fa-home text-light"></i></a>
                <a href="{% url 'todo_index' %}" class="pl-2"><i class="fas fa-list-alt text-light"></i></a>
            </nav>
        </header>
        
                {% block content %}{% endblock %}
        
        <footer class="row bg-dark pt-3">
            <div class="col-md-12 text-center text-light">
                <img id="dan-pic" src="http://saigon.ro/img/d3.jpg" class="rounded-circle m-3" ald="Dan Dumitrache - Full stack web developer">
                <p>Dan Dumitrache | Portfolio Project<br>
                Code Institute, Dublin<br>
                Jan 2018</p>
            </div>
        </footer>
    </div>
    
    <!-- =========== Bootstrap JavaScript ========== -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <!-- =========== jQuery ========== -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <!-- =========== Popper ========== -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>

</body>
</html>

Continue reading

Building a To Do Application in Python using Django Framework – Part 04

In this fourth part we need to create a super user and make migrations. Once we have a username and a password we can connect to our admin panel and create todo items.

Step 1 – Make migrations and migrate

Before we can do anything in our admin panel we have to make migrations and migrate. This will create the tables in the database. This is easily done by running the following command in the terminal:

ddnro:~/workspace/todoapp $ python3 manage.py makemigrations
Migrations for 'todo':
  todo/migrations/0001_initial.py
    - Create model TodoItem

Continue reading

Building a To Do Application in Python using Django Framework – Part 03

In this third part we are going to create the model for out todo item. The model is going to be created into the file named models.py from within the folder todo. So, in the models.py file paste the following code:

from django.db import models

class TodoItem(models.Model):
    name = models.CharField(max_length = 30, blank = False)
    done = models.BooleanField(blank = False, default = False)
    
    def __str__(self):
        return self.name

Continue reading

Building a To Do Application in Python using Django Framework – Part 02

In this second part we are going to create the URLs and the views for our ToDo application. Let’s get started!

Step 1 – Creating URLs to the home app and todo app

In the todoapp folder (which is the project) we have a file named urls.py. I modify it to look like shown below:

from django.conf.urls import url, include
from django.contrib import admin
import home.views as home_views
from todo import urls as todo_urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', home_views.get_index, name="home"),
    url(r'^todo/', include(todo_urls)),
]

Continue reading

Building a To Do Application in Python using Django Framework – Part 01

This is a project that will be part of my portfolio. It is supposed to showcase the usage of forms in Django.

For this project I am going to use Cloud 9, which is an online IDE (www.c9.io). Just create a new blank workspace on cloud 9 for this project and you are good to go.

The to do app has to have the following features:

  • A home page with a short description of the app
  • A to do page where you can add, edit, and delete a to do item

Continue reading

MySQL / SQL – Join 3 tables together and filter the result

I have looked at how to create queries using two tables. What if I need to join 3 tables to create a more complex query?

Let’s say for example that I need to create a query that shows the name of a track, the name of it’s MediaType, and the name of it’s genre. For that I will need to join 3 tables together with the appropriate join columns then I will have to add a filter to only show tracks with a MediaType of “Protected AAC audio file” and a Genre of “Soundtrack”.

As always, I need to get to the sql prompt. For that I need to run the following commands in the terminal:

service mysql start
mysql -u root -p
use Chinook;

Now, I need to take a look at the tables I need to use: Track, MediaType, and Genre.

mysql> show tables;
+-------------------+
| Tables_in_Chinook |
+-------------------+
| Album             |
| Artist            |
| Customer          |
| Employee          |
| Genre             |
| Invoice           |
| InvoiceLine       |
| MediaType         |
| Playlist          |
| PlaylistTrack     |
| Track             |
+-------------------+
11 rows in set (0.00 sec)

The above command lists all the tables from the Chinook database. To display the tables I want the desc command is used.

Continue reading

How to solve a string “splosion” problem in Python using for loop

First of all, what is a string “splosion”. Let’s consider a non-empty string, “hello” for example. You will need to return a string like “hhehelhellhello”.

def stringSplosion(initial_string):
	resulted_string = ""
	for s in range(len(initial_string)):
		resulted_string = resulted_string + initial_string[:s+1]
	return resulted_string

So, we declare a function called stringSplosion which takes in an argument, the string initial_string.
Within the function we create an empty string which is going to be our result.
Now, we start iterating over the initial string. Every time we iterate we add the characters from the beginning of the string up to the s plus 1.

Continue reading

06 – Form filters in jQuery

Many times you need to select elements that are part of a form. For example you might want to select all check-boxes that are selected.

You could match by attribute $('input[type="checkbox"][checked]'); but that will match only the initial state (specified in HTML markup).

What you want to do is to check its state in real time. For that you have to use the CSS pseudo-class :checked. This pseudo-class matches all the elements that are in the checked state. So, you should write something like shown below:

$('input[type="checkbox"]:checked');

You may also want to combine the custom jQuery selector :checkbox with the CSS pseudo-class :checked to create a very powerful custom filter.

$('input:checkbox:checked');

Continue reading