Category Archives: Python

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

Classes and OOP in Python – Part 2

Objects coded with classes intercept and respond to operations that work on built-in types: addition, slicing, printing, qualification, and so on. This is called operator overloading.

We will start with the example from “Classes and OOP in Python – Part 1”:

class MainClass:
	def setdata(self, value):
		self.data = value
	def display(self):
		print(self.data)

class ChildOneClass(MainClass):
	def display(self):
		print('Current value = "%s"' % self.data)

Now, we are going to create a third class which will be a subclass of ChildOneClass.

class GrandChildClass(ChildOneClass):
	def __init__(self, value):
		self.data = value
	def __add__(self, other):
		return GrandChildClass(self.data + other)
	def __str__(self):
		return '[GrandChildClass: %s]' % self.data
	def mul(self, other):
		self.data *= other

Continue reading

Classes and OOP in Python – Part 1

Classes are Python’s main object-oriented programming (OOP) tool. Classes are created with the statement class.

Classes generate one or more objects. Every time we call a class, we generate a new object with a distinct namespace. Each object generated from a class has access to the class’s attributes and gets a namespace of its own.

Note:
By redefining a class attributes you create a subclass.

Continue reading

Argument-Passing in Python

In Python the argument passing refers to the way objects are sent to functions as inputs. Arguments are also known as parameters.

Arguments are passed by assignment. These are the main points in passing arguments to functions:

  • Arguments are passed by automatically assigning objects to local variable names.
  • Assigning to argument names inside a function does not affect the caller.
  • Changing a mutable object argument in a function may impact the caller.
  • Immutable arguments are effectively passed “by value”. For example, integers and strings are passed by object reference instead of by copying.
  • Mutable arguments are effectively passed “by pointer”. For example, lists and dictionaries are also passed by object reference. Mutable objects can be changed in place in the function.

Continue reading

The nonlocal Statement in Python 3

In Python 3 we can change enclosing scope variables by declaring them in nonlocal statements, so nested defs can have access to names in enclosing functions.

  • The nonlocal declares that a name will be changed in an enclosing scope.
  • The nonlocal applies to a name in an enclosing function’s scope.
  • The nonlocal names must already exist in the enclosing function’s scope when declared. They can exist only in enclosing functions and cannot be created by a first assignment in a nested def.

Continue reading