Django

Django is the most popular web framework for Python.

Why Django?

Django organizes your website into apps.

It has an template engine, database support, an ORM, automatic admin interface, URL routing and way more.

You may like: Python and Django Full Stack Web Developer Bootcamp

Apps

Every app is a component of a website, these apps can be reused in other websites. An app can be anything from a poll, blog to a forum.

In the long run that will save you a lot of development time.
It’s also easy to add apps from other projects. Apps are pluggable.

Each app has its own views and models.

  • Models: store the apps data. If you want a dynamic website (using database), you need models!
  • Vies: python functions that return the webpages users see. They often use models to retrieve the data.

Inside the project directory, each app has its own directory.

Note: In the models, an object relational mapper (ORM) can be used. An ORM maps Python objects to the MySQL database, meaning you don’t have to write SQL queries.

Template engine

Django has a template language out of the box. Inside HTML, tags can be used.
If you want to print a variable:

You can loop through a list in a template:

Even if statements can be used in a template:

You may like: Python and Django Full Stack Web Developer Bootcamp

Admin Interface

Django comes with an admin interface!

It’s tedious work to create admin sites for clients to edit database data.
Django automates creation of admin interfaces for models.

django admin interface

Forms

Even forms come with Django. Automatic input validation, generate forms, convert data to python datatypes

Installing Django

Install Django?

We recommend to install Python 3 and pip3.

To test your Python version, open the command prompt and type:

python –version

On some systems both versions of Python are installed, in that case use python3.

Note: Django works with both versions of Python, but Python 2 is a legacy version.

 

You may like: Python and Django Full Stack Web Developer Bootcamp

Installing Django

We use pip to install django:

pip3 install django

We then see:

pip3 install django
[sudo] password for user:
Collecting django
Downloading Django-1.11.3-py2.py3-none-any.whl (6.9MB)
100% |████████████████████████████████| 7.0MB 107kB/s
Requirement already satisfied: pytz in /usr/lib/python3.6/site-packages (from django)
Installing collected packages: django
Successfully installed django-1.11.3

Django version

You can check your version using Python.

On Liux and Mac OS X:

python3 -m django –version

On windows:

py -3 -m django –version

Starting a django project

Start a new Django project?.

After installation of Django, we can create a new project.

Django can be used to create websites and web apps. You need to type in some terminal
commands to start a new Django project.

You may like: Python and Django Full Stack Web Developer Bootcamp

Create Django project

Open the command prompt, then enter your projects directory.

mkdir projects
cd projects
mkdir django_example
cd django_example

Then we use django-admin tool.

django-admin startproject mywebsite
cd mywebsite
Note: If you list the files in the new directory, you’ll see manage.py and the skeleton project.

Django start server

Start the developent web server.

python manage.py runserver

It’ll output lots of things:

Performing system checks…

System check identified no issues (0 silenced).

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run ‘python manage.py migrate’ to apply them.

July 19, 2017 – 20:54:09
Django version 1.11.3, using settings ‘mywebsite.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Note: On the last line, you’ll see the address: http://127.0.0.1:8000/
Open that address in your webbrowser.

 
You’ll see the basic Django template:

django new project

 
If you see this screen, you have now successfully created a new Django project.

Django hello world

Create hello world in django?

In this article we’ll create the hello world app.

If you do not have Django installed, see the previous tutorials.

You may like: Python and Django Full Stack Web Developer Bootcamp

Make a new project

Execute these commands:

django-admin startproject first_django_project
cd first_django_project/
python manage.py startapp hello

Wait.. what did we just do?

  • We created a project named first_django_project
  • We created an app named hello

Django projects can have multiple apps. Every app is like a website component,
it has unique functionality.

Hello world code

We create the hello world code.
If you open the folder /first_django_project/hello you’ll see this:

django app

A lot of code! Which file do we need to change?

There’s one file named views.py

If you open the file you’ll see this:

We’re gonna create our view in here.

Note: A view returns what the visitor sees: a webpage.

 
We’ll use HTML and a class to create the view.

If you are not familiar with these, I recommend this course:
Python and Django Full Stack Web Developer Bootcamp

Add these lines of code:

We create a class HomePageView with the method dispatch.
This methods return the webpage code (in HTML).

URL router

Python needs to return the view, if we visit the webpage.

If we visit a webpage, the web browser sends a HTTP request.
To link views with the HTTP request, we create a new route.

 
In the app directory, create the file hello/urls.py with this content:

In the project directory, change /first_django_project/urls.py:

Change app settings

Then we edit first_django_project/settings.py. Apps can be added or removed in this file.
You’ll see a list definition:

Add our hello app to this list.

We’ll remove the line SessionAuthenticationMiddleware.
Finally we’ll disable the database. This is defined somewhere on line 72.

Remove those lines.

All set!

Run the command:

python manage.py runserver

Then open the URL to see the result:

django hello world

If you see the above result, you completed this lesson!

Django models

What is a django model?

A model is a class that matches a database table (or collection).
Models are defined in the apps models.py file, /app/models.py.

Say what? Let’s make an app with a database model!

You may like: Python and Django Full Stack Web Developer Bootcamp

Models example

We start a new project, movie database.

django-admin startproject movie_site

Inside the directory movie_site we now see:

manage.py movie_site

Configure database

Open movie_site/settings.py, there are the lines:

A database is already set up!

We’ll use the default database system: sqlite3.

Note: Django supports many databases including:

  • SQLite (django.db.backends.sqlite3)
  • MySQL (django.db.backends.mysql)
  • MongoDB (django_mongodb_engine)
  • Oracle (django.db.backends.oracle)
  • PostGreSQL (django.db.backends.postgresql_psycopg2)
  • NoSQL DB

 
Create your database with this command:

python manage.py migrate

Now you’ll see lots of lines:

Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial… OK
Applying auth.0001_initial… OK
Applying admin.0001_initial… OK
Applying admin.0002_logentry_remove_auto_add… OK
Applying contenttypes.0002_remove_content_type_name… OK
Applying auth.0002_alter_permission_name_max_length… OK
Applying auth.0003_alter_user_email_max_length… OK
Applying auth.0004_alter_user_username_opts… OK
Applying auth.0005_alter_user_last_login_null… OK
Applying auth.0006_require_contenttypes_0002… OK
Applying auth.0007_alter_validators_add_error_messages… OK
Applying auth.0008_alter_user_username_max_length… OK
Applying sessions.0001_initial… OK

Good job!

Create an app

Django sites can have many apps. Each app is like a plugin.

Let’s make a movie details app.

python manage.py startapp movies

You have just created an app!
There’s a new folder: movies.

Note: Django doesn’t know it should use this app yet.
Apps are not added by default.. Let’s teach django.

 

Open movie_site/settings.py.
Scroll down to the line INSTALLED_APPS and add the line ‘movies’.

Create a movie model

We can create our model now. In the movies/models.py you can define all models.
Create a class for your movies model. The class will map to the database table.

If you don’t know classes and object orientated programming, take this couse:
Python and Django Full Stack Web Developer Bootcamp

We class will contain attributes of our movie object.

Run the command;

python manage.py makemigrations movies

This will output:

Migrations for ‘movies’:
movies/migrations/0001_initial.py
– Create model Movie

Also type this command:

python manage.py migrate movies

The magic continues:

Operations to perform:
Apply all migrations: movies
Running migrations:
Applying movies.0001_initial… OK

In English, that means it’s just created our database table!

Browse database

Open the database file (db.sqlite3) with sqlitebrowser.

django database model

Yeehaw! Our movie model is now our database.

Django admin

Django comes with an automatic admin interface.

We just created a (database) model in the previous article. Now we can create a backend management tool for it.

This is one of the most powerful features of Django.

You may like: Python and Django Full Stack Web Developer Bootcamp

Admin interface

You can open the admin interface with a web browser, but to open the admin interface, first we need to change a file. Open the file movies/admin.py
This is the file contents:

Lets add some code:

Start the Django server:

python manage.py runserver

Open the url: http://127.0.0.1:8000/admin/

Admin login

Note: that’s http://127.0.0.1:8000/admin/

 
A login screen will popup. Let’s enter the matrix!

django admin

Django admin add user

Create a superuser.

python manage.py createsuperuser

Type a username and password. You should see this message:

Superuser created successfully.

Now open the webpage again and login.

The admin screen

If you see the screen below, good job!

django site admin

The model ‘Movie’ is there!

Django admin add

If you click on the model, a new screen shows up:

django add to model

We can add new movies here. If you click on the button, all the fields are there to add a new movie, exactly as we specified it in the model.

django insert into database

How cool is that?
All the CRUD operations work.

Note: CRUD is short for create, read, update and delete. Common database operations

 
We can now interact with the complete database system from this graphical interface.

Getting started

To get started, you will need the Python interpreter or a Python IDE. An IDE is a tool that will make the experience of software development much better.

Related course:

Python interpreter

You can download Python interpreter here: https://www.python.org/downloads/
The Python interpreter is a command line program, we’ll discuss it in the next lecture.

Python programs are simply a collection of text files.  If you want something more sophisticated than notepad for editing, you will need a Python IDEs (recommend). A Python IDE will make programming Python easier.

Python IDE

An IDE generally supports listing all program files, syntax highlighting and other features. There are lots of Python IDEs you could choose from.

Using one of these Python IDEs makes programming easier than in say, notepad. It will automatically color the text like the example below:

Machine Learning

What is Machine Learning?
The word ‘Machine’ in Machine Learning means computer, as you would expect.
So how does a machine learn?

A computer can use data, as it’s doing right now (this webpage is data). Given
data, we can do all kind of magic with statitics. So can computer algorithms.

These algorithms can solve problems including prediction, classification and clustering.
A machine learning algorithm will learn from new data.

Types of learning

There are two types of learning: supervised learning and unsupervised learning.. Say what?



Let’s suppose we have consumer data. I tell the computer: these customers have a high income, those customers have median income. The training phase.
Then we can ask this computer:

With unsupervised learning algorithms, you have no idea. You give the data to the computer and expect answers. Surprisingly, these work rather well.

Machine Learning Tasks

All of the Machine Learning algorithms take data as input, but what they want to achieve is different.

They can be broadly be classified in a few groups based on the task they are designed to solve. These tasks are: classification, regression and clustering.

 
Classification
If we have data, say pictures of animals, we can classify them. This animal is a cat, that animal is a dog and so on. A computer can do the same task using a Machine Learning algorithm that’s designed for the classification task. In the real world, this is used for tasks like voice classification and object detection. This is a supervised learning task, we give training data to teach the algorithm the classes they belong to.

Regression
Sometimes you want to predict values. What are the sales next month? What is the salary for a job? Those type of problems are regression problems. The aim is to predict the value of a continous response variable. This is also a supervised learning task

Clustering
Clustering is to create groups of data called clusters. Observations are assigned to a group based on the algorithm. This is an unsupervised learning task, clustering happens fully automatically. Imagining have a bunch of documents on your computer, the computer will organize them in clusters based on their content automatically.

bag of words

If we want to use text in Machine Learning algorithms, we’ll have to convert then to a numerical representation. It should be no surprise that computers are very well at handling numbers.

We convert text to a numerical representation called a feature vector. A feature vector can be as simple as a list of numbers.

The bag-of-words model is one of the feature extraction algorithms for text.

Feature extraction from text

The bag of words model ignores grammar and order of words.
We start with two documents (the corpus):

‘All my cats in a row’,
‘When my cat sits down, she looks like a Furby toy!’,

 
A list in then created based on the two strings above:

{‘all’: 0, ‘cat’: 1, ‘cats’: 2, ‘down’: 3, ‘furby’: 4, ‘in’: 5, ‘like’: 6, ‘looks’: 7, ‘my’: 8, ‘row’: 9, ‘she’: 10, ‘sits’: 11, ‘toy’: 12, ‘when’: 13 }

 
The list contains 14 unique words: the vocabulary. That’s why every document is represented by a feature vector of 14 elements. The number of elements is called the dimension.

Then we can express the texts as numeric vectors:

[[1 0 1 0 0 1 0 0 1 1 0 0 0 0]
[0 1 0 1 1 0 1 1 1 0 1 1 1 1]]

 
Lets take a closer look:

‘All my cats in a row’ = [1 0 1 0 0 1 0 0 1 1 0 0 0 0]

 
If we follow the order of the vocabulary:
 
bag of words, feature extraction

we’ll get a vector, the bag of words representation.

Bag of words code

We’ll define a collection of strings called a corpus. Then we’ll use the CountVectorizer to create vectors from the corpus.