The Essence of Python 3.6+ with Django 2.1+ Framework

In today’s event loop on {{ PLP }}, which is the Basics of Python 3.6+ Programming with Django 2.1+ framework.

Python was created by Guido van Rossum that was first conceived in the late 1980s.  It’s an interpreted high-level programming language for general-purpose programming.

The first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace.

Introduction

Welcome to our first ever Python 3.6+ event loop on {{ PLP }}, are you ready on our nice and easy topic for today?

In this event, I’ll be focusing more on direct to the point, real-life scenarios in the work-related matter on how we can apply this knowledge to your future work as a developer using Python 3.6+ with Django 2.1+ framework.

Getting Started with the Basics of Python 3.6+ Programming Language

I will be concise or keep this simple, the most common usage of Python 3.6+ programming within our web-based application paradigm throughout the entire discussions.

Below are the Essence of Python programming language that you must practice, observe and follow, otherwise you’ll be getting in trouble running Python codes from the interpreter when you run you’re first ever Python snippets.

The Essence of Python Code

Python code has it’s elegant and clean way of coding style as a standard way of coding for developers with more emphasis on the code readability.  Meaning, it uses either Tab or White Space but I preferred to use the Tab.

You can’t use single white space at the same time you use the tab with 4 spaces by default.  It’s not allowed and it will return an error from the Python interpreter by itself. 

We want to see the exact thrown error from the interpreter.

1.  Use Tab with 4 Spaces by Default

In this actual example, we will first access our web console to write a command, just in case you missed out on how to access your web console using “Lish Console“, just do a quick check on that previous event loop.  All right, let’s get started on this.

1
2
3
4
root@localhost:~# python3
Python 3.6.6 (default, Sep 12 2018, 18:26:19)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.

After successful login to our “root” access, execute this command “python3” so we can now use the Python interpreter from our web console.  Awesome, I’ll give you the basic code snippets to illustrate what code readability means for Python.

1
2
3
4
5
6
7
v = 10
if v >= 10:
r = 1
File "<stdin>", line 2
r = 1
^
IndentationError: expected an indented block

To assign the value for variable “v” in Python, no need for you to declare Int or Integer as Python automatically treats the variable as the integer.

The “if” block statement always ends with “:colon, later I’ll be stating in details for more understanding on the essence of Python codes.

As you can see, I didn’t use Tab that usually provides with 4 spaces by default, after the “if” line statement, it will throw an “IndentationError: expected an indented block“.

As this error clearly stated that we need to use the indention after any conditional statements like “if“, “else“, “for” loop, “elif” as else if statement, “with“, “def()” for function declaration, etc. too many to mention as of the moment, I just give you some of the glance of it.

2.  Don’t Mixed the Tab with Inconsistent White Space

Now, in our next illustration, the Python code snippets below that shows, I have an inconsistent tab and spaces.  See the actual code below.

1
2
3
4
5
6
7
8
v = 10
if v >= 10:
   r = 1
    a = 1
File "<stdin>", line 3
a = 1
^
TabError: inconsistent use of tabs and spaces in indentation

What I did is that, at line number 3, I give 3 white spaces for the variable assignment r = 1 and at line number 4 I give 1 Tab with 4 whites spaces by default.  As the code above clearly thrown an error from the Python interpreter like “TabError: inconsistent use of tabs and spaces in indentation“.

My Personal Recommendation:  Use the Tab space with 4 default spaces when you start coding with Python.  Remember, this is one of the essences of Python code.

3. Variable Assignment

The variable assignment for Python is nice and easy as well.  See examples below:

1
a, b = 0, "Hello World!"

Simple one line of code assignment can be possible with Python.  As you can see the above example is that variable a and b separated with comma symbol and then at the right assignment are the initial values for these 2 variables separated with comma as well.  Awesome right?

Furthermore, you can also do the typical variable assignment with each lines of code like for example.

1
2
a = 0
b = "Hello World!"

Again, no need to identify the variable as String or Integer, unlike the other programming languages.

List Comprehension

Assigning the list comprehension variable is easy as well, it’s required to use the “[]” bracket separated with comma as well.

1
fruits = ['Banana', 'Apple', 'Lime']

For most of the cases, we need to loop and read what’s data inside of a list in Python, by the way, in other programming language they called it an “array“.

1
2
3
4
5
6
7
fruits = ['Banana', 'Apple', 'Lime']
for fruit in fruits:
    print(fruit)

Banana
Apple
Lime

You can also take a look from Python documentation for more examples about the list comprehension as well.

4.  Function Declaration and it’s Structure

Why we need a function? and what’s the use of it for us when we kick start our web based application topic with Django 2.1+ framework?

Essentially, the Function is really callable and re-usable code to be executed when we need it the most.  No need to write the same code all over again throughout your entire application to be developed soon.

For example, we shall write some basic function in Python for us to sum up 2 numbers.

1
2
3
4
5
6
def add_me(a, b):
    return a + b

v = add_me(1, 1)
print(v)
2

As you can see from the code snippet above shows that I created the basic function from Python interpreter. 

The “def” must be all small letters and all the parameter variables or in other term is an “argument” as well.  If you mistakenly make like “Def” or something like all capital letters, the interpreter will throw an error saying that “SyntaxError: invalid syntax“.

Again, this is one of the essences of the Python codes so you need to remember this as well.

Function with Optional Arguments

In this case, we have a required positional argument variable as “a” with the optional argument of “b” variable assigned with “None” as the default value.  In order for a function with optional arguments to be fulfilled, you need to specify that optional variable with “None” value.

Furthermore, please remember that required arguments are always in the first line of variables set and then the optional is always at the end together.  Meaning, you need to group the required arguments first and then the optional ones.

You can’t re-arrange the sequence for both required and optional arguments.

Please take note on this, I’ve mix the required and optional arguments together and see the thrown error from the Python Interpreter by itself.

1
2
3
4
5
def try_opt(a, b=None, c):
    return a, b, c

File "<stdin>", line 1
SyntaxError: non-default argument follows default argument

The error “SyntaxError: non-default argument follows default argument” clearly stated that you can’t be mixed both, so this is another essence of the Python code.

Function with Extra Processing

Actually, you can do more incredible things inside a function in Python, you can do extra processing inside of it.  See the example basic code snippet for your understanding.

1
2
3
4
5
6
7
8
9
10
11
def get_lowest_number(a, b):
    lowest_num = 0
    if a < b:
        lowest_num = a
    else:
        lowest_num = b
    return lowest_num

v = get_lowest_number(1, 2)
print('The lowest number is: %s' %v)
The lowest number is: 1

As you can observe that the “print” statement from Python which is to display the output or the result from the interpreter is having “%s” which means it’s a placeholder variable and you can have multiple “%s” placeholder of any types of data to be placed at that certain position from an output string.  In some common programming terms is a concatenation between a series of strings.

At the other right side of the variable name, “%v” is the value that corresponds to a variable “v” of whatever the value of it will be displayed from the print statement with the corresponding placeholder.

I’ll show you another example of multiple placeholders from a print statement.

1
2
3
4
5
6
7
8
9
10
11
12
def get_lowest_number(a, b):
    lowest_num = 0
    if a < b:
        lowest_num = a
    else:
        lowest_num = b
    return lowest_num

v = get_lowest_number(1, 2)
m = "Awesome!"
print("The lowest number is: {v}, {m}".format(v=v, m=m)
The lowest number is: 1, Awesome!

The “{variable}” inside of a curly bracket is the placeholder with the specific assignment inside the “.format()” statement.   Whatever your variable name inside the “{variable}” placeholder would be the exact name of that variable name with the value assignment inside the “.format()” statement.

By the way, the “.format()” statement can be of any data types.

5.  If Else Statement

The most common statement in any programming language is the conditional statement like the “If Else” statement.  In Python, you can do this easily.

1
2
3
4
5
6
price = 3
is_price_exist = False
if price > 0:
    is_price_exist = True
else:
    is_price_exist = False

It’s easy, right? did you notice that I introduce to you the Boolean condition in the presence of the “is_price_exist” variable?  In Python, Boolean or the True or False statement the first letter must always be the capital letter.

You can also do it without the “Else” statement from this example since we already initialized our “is_price_exist” variable as “False” before the “If” statement begin.

1
2
3
4
price = 3
is_price_exist = False
if price > 0:
    is_price_exist = True

Another example of the “If Else If and Else” statement.

1
2
3
4
5
6
7
name = "John Doe" # This is a sample inline comment
if len(name) >= 10:
    print("Good long Name")
elif len(name) > 3 and len(name) < 10:
    print("Good short Name")
else:
    print("Name is too short")

As you can see at line number 1 “name = “John Doe” # This is a sample comment line I purposely include single line comment to display how we can do the inline comment from the Python code.

And this is for the multiple comments you can wrap with a triple-double quote.

1
2
3
4
5
"""
This is an example of a multiple comment line for Python code.
Another comment line here.
And here.
"""

Getting the Length of the Strings

Another common usage of Python is getting the length of the strings or list of a given variable.

1
2
3
name = "John Doe"
print(len(name))
8

The code snippet above, we use the built in function name “len()” from Python with the small letter “l“, please remember that all functions and libraries from Python are all small letters.

Another good usage of getting the “len()” function from a list variable.

1
2
3
fruits = ['Banana', 'Apple', 'Lime']
print(len(fruits))
3

For Loop

The built-in “for” loop expression is one of the most common usages we will be using throughout a few web-based projects we will be discussing later on.   So this is just a basic usage of “for” loop in Python.

1
2
3
4
5
6
7
fruits = ['Banana', 'Apple', 'Lime']
for fruit in fruits:
    print(fruit)

Banana
Apple
Lime

This is just a tip of the iceberg of using Python 3 with tons of useful libraries and built-in functions that we can use for our web-based applications when we start doing simple projects first with Django 2.1 framework for better understanding.

Getting Started with the Basics of Django 2.1 + Framework

In the web-based development workload, it’s always been painful if we don’t use the web framework for a certain programming language.  Every developer needs a tool to ease out our workloads in developing web-based projects and that’s why Django is our friend that really do the heavy lifting for us.

We just focused on creating solutions, layout our plans and execute it in a rapid development without sacrificing the quality, web security, clean and pragmatic Pythonic codes with the help of Django as our web framework.

The Essence of Django 2.1 Framework for Python

Django is a high-level Python Web framework that was built with complete solutions that deliver rapid development and deployment.

The simplicity of Django with tons of built-in functions and clean project structures that has the concept of making multiple application that you can attach to your main project.

What I mean of attaching multiple applications that you’ve done developing like for example, you make a Comment System where your users can be able to comment from your web-based project like the product page where your users can be able to comment or submit a review, and you would like to include it in your another Django project site so you don’t want to make another Comment System for every projects all over again.

This is called a micro-services as well, we will be further discussing this topic in our future engagement with Django.

The Most Common Built-in Applications from Django for our Web Development Projects.

The list of the most common built-in systems that we can use for the web-based projects that Django promised to deliver to us for our rapid development and deployment.

1.  User Authentication System

One of the biggest heavy lifting for us, when you use Django as our web-framework for Python, is the built-in User Authentication System that was made solely by the core Django developers that is natively supported by them with the complete user authentication from creating users, login authentication, password reset, changing the password, creating a superuser, log out user account and permissions and authorization.  This is incredible isn’t? Great!

I’ll be illustrating the default User Authentication system provided by Django when we start the small project that would showcase the complete power of user auth model from Django.

2.  The Django Admin Site

Django admin site is very powerful backend site administration where you can fully manage your backend database for your CRUD (Create, Read, Update and Delete) operations that really minimizes the very critical operation on accessing your production database in any critical circumstances.

It’s a very convenient and powerful enough to automate the backend database administrator’s task embedded with the proper logging system for auditing purposes as well.  Rest assured, we will be tackling this further during our actual development later on.

3.  Models and Databases

Instead of creating tables directly from a database server, Django provided with robust ORM (Object-relational Mapping) technology that we can define our database with table collections directly from Django Models.

A very quick and basic example of Django Models that best describes of what is Django Models is all about and this is one of the essences of Django that serve as a life-blood of our web-based application system when we’re dealing with databases.

1
2
3
4
5
from django.db import models

class Profile(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

The class name “Profile” means that this is the table name that Django Models will automatically create for us with the collection of fields which are the “first_name” and the “last_name” both are character strings as data type, in MySQL field data type equivalent to a “varchar” with the maximum length of 30 characters including white spaces.

In the meantime, these are the few common essences of Python and Django that we’re about to cover throughout the entire development process later on.

In the next event loop on {{ PLP }}.

So much of information to digest for now and I know you’re getting excited as we go down deeper on our learning with Python and Django and I can understand it’s not easy to learn new things especially in the programming world.

Up next, we’re about to start preparing what would be the ideal project layout for Django to start with.  Are you getting excited? Stay tuned for more!

See you in the next event loop on The Ideal Django Project Structures.

That’s all, have fun learning with {{ PLP }}.

To help Filipino students to learn Python programming language with Django to enhance their capabilities in developing robust web-based applications with practical and direct to the point tutorials, step-by-step with actual information that I provided for you. Leave a comment below or email me at [email protected], thank you!