Installing Django

There are two very important things you need to do to get started with Django:

  1. Install Django (obviously); and
  2. Get a good understanding of the Model-View-Controller (MVC) design pattern.

The first, installing Django, is really simple and detailed in the first part of this chapter. The second is just as important, especially if you are a new programmer or coming from using a programming language that does not clearly separate the data and logic behind your website from the way it is displayed.

Django’s philosophy is based on loose coupling, which is the underlying philosophy of MVC. We will be discussing loose coupling and MVC in much more detail as we go along, but if you don’t know much about MVC, then you best not skip the second half of this chapter, because understanding MVC will make understanding Django so much easier.

Installing Django

Before you can start learning how to use Django, you must first install some software on your computer. Fortunately, this is a simple three step process:

  1. Install Python.
  2. Install a Python Virtual Environment.
  3. Install Django.

If this does not sound familiar to you don’t worry, in this chapter I assume you have never installed software from the command line before and will lead you through it step by step.

I have written this section for those of you running Windows. While there is a strong *nix and OSX user base for Django, most new users are on Windows. If you are using Mac or Linux, there are a large number of resources on the Internet; with the best place to start being Django’s own installation instructions.

For Windows users, your computer can be running any recent version of Windows (7, 8.1 or 10). This chapter also assumes you’re installing Django on a desktop or laptop computer and will be using the development server and SQLite to run all the example code in this book.

This is by far the easiest, and best way to set up Django when you are first starting out. If you do want to go to a more advanced installation of Django, your options are covered in Chapter 13 – Deploying Django, Chapter 20 – More on installing Django and Chapter 21 – Advanced Database Management.

Installing Python

Django itself is written in Python, so the first step in installing the framework is to make sure you have Python installed.

Python Versions

Django 1.11 LTS works with Python version 2.7, 3.4, 3.5 and 3.6. For each version of Python, only the latest micro release (A.B.C) is officially supported, although from experience, any recent release works fine.

Installation

If you’re on Linux or Mac OS X, you probably have Python already installed. Type python into your terminal and if you see something like the following, then Python is installed:

Python 2.7.10 (default, Feb 6 2017, 23:53:20)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)]
on darwin
Type "help", "copyright", "credits" or "license" for more
information.
>>>

Assuming Python is not installed in your system, go to https://www.python.org/downloads/ and click the big yellow button that says “Download Python 3.x.x”. At the time of writing, the latest version of Python is 3.6.1, but it may have been updated by the time you read this, so the numbers may be slightly different.

As I stated before, DO NOT download version 2.7.x as this is the old version of Python. All of the code in this book is written in Python 3, so you will get compilation errors if you try to run the code on Python 2.

Once you have downloaded the Python installer, go to your Downloads folder and double click the file “python-3.x.x.msi” to run the installer.

The installation process is the same as any other Windows program, so if you have installed software before, there should be no problem here, however there is one extremely important customization you must make.

By default, the Python executable is not added to the Windows PATH statement. For Django to work properly, Python must be listed in the PATH statement. Fortunately, this is easy to rectify – when the Python installer screen opens, make sure “Add Python 3.6 to PATH” is checked before installing (Figure 1-1).

Installing Django - Add Python to PATH.
Figure 1-1: Check the ‘Add Python 3.6 to PATH’ box before installing.

Once Python is installed, you should be able to re-open the command window and type python at the command prompt and get something like this:

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

You may have to restart Windows to get this to work. While you are at it, there is one more important thing to do. Exit out of Python, then enter the following at the command prompt:

python -m pip install -U pip 

This command will either print a message saying pip is up to date, or give an output similar to this:

C:\Users\nigel>python -m pip install -U pip 
Collecting pip
Downloading pip-8.1.2-py2.py3-none-any.whl (1.2MB)
    100% |################################| 1.2MB 198kB/s 
Installing collected packages: pip 
Found existing installation: pip 7.1.2
Uninstalling pip-7.1.2:
    Successfully uninstalled pip-7.1.2 
Successfully installed pip-8.1.2 

You don’t need to understand exactly what this command does right now; put briefly pip is the Python package manager. It’s used to install Python packages – pip is actually a recursive acronym for “Pip Installs Packages”. Pip is important for the next stage of our install process, but first we need to make sure we are running the latest version of pip, which is exactly what this command does.

Installing a Python Virtual Environment

All of the software on your computer operates interdependently – each program has other bits of software that it depends on (called dependencies) and settings that it needs to find the files and other software it needs to run (call environment variables).

When you are writing new software programs, it’s possible (and common!) to modify dependencies and environment variables that your other software depends on. This can cause numerous problems, so should be avoided.

A Python virtual environment solves this problem by wrapping all the dependencies and environment variables that your new software needs into a file system separate from the rest of the software on your computer.

The virtual environment tool in Python is called virtualenv and we install it from the command line using pip:

pip install virtualenv 

The output from your command window should look something like this (your version numbers may be different):

C:\Users\nigel>pip install virtualenv 
Collecting virtualenv 
Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB)
    100% |################################| 1.8MB 323kB/s 
Installing collected packages: virtualenv 
Successfully installed virtualenv-15.1.0 

Creating a Project Directory

Before we create our Django project, we first need to create a project directory. The project directory can go anywhere on your computer, although it’s highly recommended that it be created somewhere in your user directory so you don’t get any permission issues later on. A good place for your folder in Windows is your My Documents folder.

Create a new folder on your system, I have called the folder mysite_project, but you can give the folder any name that makes sense to you.

For the next step, you need to be in a command window (terminal on Linux and OS X). The easiest way to do this on Windows is to open Windows Explorer, hold the shift key and right click the folder to get the context menu and click on “Open command window here” (Figure 1-2).

Open a command window on Windows
Figure 1-2: Hold the shift key and right-click a folder to open a command window.

Once you have created your project folder, you need to create a virtual environment for your project by typing virtualenv env_mysite at the command prompt you just opened:

 C:\Users\nigel\OneDrive\Documents\mysite_project> virtualenv env_mysite

Again, the name of the virtual environment is not important, you can change the name to suit. On my system, the output from this command looks something like this:

Using base prefix 'c:\\users\\nigel\\appdata\\local\\programs\\python\\python36-32'
New python executable in C:\Users\nigel\OneDrive\Documents\mysite_project\env_mysite\Scripts\python.exe
Installing setuptools, pip, wheel...done.

Once virtualenv has finished setting up your new virtual environment, open Windows Explorer and have a look at what virtualenv created for you. In your project directory, you will now see a folder called \env_mysite (or whatever name you gave the virtual environment). If you open the folder, you will see the following:

\Include 
\Lib 
\Scripts 
pip-selfcheck.json

If you look inside the \Lib folder, you will see virtualenv has created a complete Python installation for you, separate from your other software, so you can work on your project without affecting any of the other software on you system.

To use this new Python virtual environment, we have to activate it, so let’s go back to the command prompt and type the following:

env_mysite\scripts\activate

This will run the activate script inside your virtual environment’s \scripts folder. You will notice your command prompt has now changed:

(env_mysite) C:\Users\Nigel\OneDrive\Documents\mysite_project>

The (env_mysite) at the beginning of the command prompt lets you know that you are running in the virtual environment. Our next step is to install Django.

Installing Django

Now that we have Python and are running a virtual environment, installing Django is super easy, just type the command:

pip install django==1.11.2 

This will instruct pip to install Django into your virtual environment. Your command output should look like this:

(env_mysite) C:\Users\nigel\OneDrive\Documents\mysite_project> pip install django==1.11.2

Collecting django==1.11.2
Using cached Django-1.11.2-py2.py3-none-any.whl
Collecting pytz (from django==1.11)
Using cached pytz-2017.2-py2.py3-none-any.whl
Installing collected packages: pytz, django
Successfully installed django-1.11.2 pytz-2017.2

In this case, we are explicitly telling pip to install Django 1.11.2, which is the latest version of Django 1.11 LTS at the time of writing. If you are installing Django, it’s good practice to check the Django Project website for the latest version of Django 1.11 LTS.

Also note my computer didn’t need to download anything as I have another virtual environment I installed today and Windows used the cached version.

And finally, note that Django 1.11 requires the Python Timezone package (pytz), so pip installs that in your virtual environment as well.

For some post-installation positive feedback, take a moment to test whether the installation worked. At your virtual environment command prompt, start the Python interactive interpreter by typing python and hitting enter. If the installation was successful, you should be able to import the module django:

(env_mysite) C:\Users\nigel\OneDrive\Documents\mysite_project> python

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.get_version()
'1.11'
>>>

Starting a Project

Once you’ve installed Python, you can take the first step in developing a Django application by creating a project. A project is a collection of settings for an instance of Django. If this is your first time using Django, you’ll have to take care of some initial setup.

Namely, you’ll need to auto-generate some code that establishes a Django project. The auto-generated code contains a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.

I am assuming at this stage you are still running the virtual environment from the previous installation step. If not, you will have to start it again with env_mysite\scripts\activate\. Also make sure you are in the mysite_project directory.

From your virtual environment command line, run the following command:

django-admin startproject mysite 

This command will automatically create a mysite directory in your project directory as well as all the necessary files for a basic, but fully functioning Django website.

Let’s look at what startproject created:

mysite/
  manage.py 
  mysite/
    __init__.py 
    settings.py 
    urls.py 
    wsgi.py 

These files are:

  • The outer mysite/ root directory. It’s just a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.
  • manage.py. A command-line utility that lets you interact with your Django project in various ways. You can read all the details about manage.py on the Django Project website.
  • The inner mysite/ directory. It’s the Python package for your project. It’s the name you’ll use to import anything inside it (e.g. mysite.urls).
  • mysite/__init__.py. An empty file that tells Python that this directory should be considered a Python package. (Read more about packages in the official Python docs if you’re a Python beginner.).
  • mysite/settings.py. Settings/configuration for this Django project. Appendix D will tell you all about how settings work.
  • mysite/urls.py. The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in Chapters 2 and 7.
  • mysite/wsgi.py. An entry-point for WSGI-compatible web servers to serve your project. See Chapter 13 for more details.

Setting Up a Database

Django includes a number of applications by default (e.g. the admin program and user management and authentication). Some of these applications make use of at least one database table, so we need to create tables in a database before we can use them. To do that, change into the mysite folder created in the last step (type cd mysite at the command prompt) and run the following command:

python manage.py migrate

The migrate command creates a new SQLite database and any necessary database tables according to the settings file created by the startproject command (more on the settings file later in the book). If all goes to plan, you’ll see a message for each migration it applies:

(env_mysite) C:\Users\Nigel\OneDrive\Documents\mysite_project\mysite>python manage.py migrate

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
### several more migrations (not shown)

The Development Server

Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already, and run the following commands:

python manage.py runserver 

You’ll see the following output on the command line:

Performing system checks...

System check identified no issues (0 silenced).
May 16, 2017 - 16:48:29
Django version 1.11, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

You’ve started the Django development server, a lightweight Web server written purely in Python. Django’s creators included this with Django so you can develop things rapidly, without having to deal with configuring a production server – such as Apache – until you’re ready for production.

Now’s a good time to note: don’t use this server in anything resembling a production environment. It’s intended only for use while developing. Now that the server’s running, visit http://127.0.0.1:8000/ with your Web browser. You’ll see a “Welcome to Django” page in pleasant, light-blue pastel (Figure 1-3). It worked!

Installing Django - Django's welcome page
Figure 1-3: Django’s welcome page