There are two very important things you need to do to get started with Django:
- Install Django (obviously); and
- 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.
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:
- Install Python.
- Install a Python Virtual Environment.
- 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 (Vista, 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 setup 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.
Django itself is written purely in Python, so the first step in installing the framework is to make sure you have Python installed.
Django version 1.8 LTS works with Python version 2.7, 3.3, 3.4 and 3.5. For each version of Python, only the latest micro release (A.B.C) is supported.
If you are just trialling Django, it doesn’t really matter whether you use Python 2 or Python 3. If, however, you are planning on eventually deploying code to a live website, Python 3 should be your first choice. The Python wiki puts the reason behind this very succinctly:
Short version: Python 2.x is legacy, Python 3.x is the present and future of the language
Unless you have a very good reason to use Python 2 (e.g. legacy libraries), Python 3 is the way to go.
NOTE: All of the code samples in this book are written in Python 3
If you’re on Linux or Mac OS X, you probably have Python already installed. Type
python at a command prompt (or in Applications/Utilities/Terminal, in OS X). If you see something like this, then Python is installed:
Assuming Python is not installed in your system, we first need to get the installer. 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.5.1, but it may have been updated by the time you read this, so the numbers may be slightly different.
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 the 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:
- In Python 3.4.x, When the installer opens the customization window, the option “Add python.exe to Path” is not selected, you must change this to “Will be installed on local hard drive” as shown in Figure 1-1.
- In Python 3.5.x you make sure “Add Python 3.5 to PATH” is checked before installing (Figure 1-2).
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:
While you are at it, there is one more important thing to do. Exit out of Python with CTRL-C. At the command prompt type, the following and hit enter:
The output will be something similar to this:
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 (8.1.2 at the time of writing), 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 is 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:
The output from your command window should look something like this:
virtualenv is installed, you need to create a virtual environment for your project by typing:
In this example, I have kept it simple as we will only be using one virtual environment for our project, so I have used “env_mysite”. The output from your command should look something like this:
virtualenv has finished setting up your new virtual environment, open Windows Explorer and have a look at what
virtualenv created for you. In your home 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:
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:
This will run the activate script inside your virtual environment’s
\scripts folder. You will notice your command prompt has now changed:
(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.
Now that we have Python and are running a virtual environment, installing Django is super easy, just type the command:
This will instruct pip to install Django into your virtual environment. Your command output should look like this:
In this case, we are explicitly telling pip to install Django 1.8.13, which is the latest version of Django 1.8 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.8 LTS.
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
Setting Up a Database
This step is not necessary in order to complete any of the examples in this book. Django comes with SQLite installed by default. SQLite requires no configuration on your part. If you would like to work with a “large” database engine like PostgreSQL, MySQL, or Oracle, see Chapter 21.
Starting a Project
Once you’ve installed Python, Django and (optionally) your database server/library, 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: 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\. From your virtual environment command line, run the following command:
This will create a
mysite directory in your current directory (in this case
\env_mysite\). If you want to create your project in a directory other than the root, you can create a new directory, change into that directory and run the
startproject command from there.
Let’s look at what
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.pyon 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/__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.
mysite/settings.py. It’s a normal Python module with module-level variables representing Django settings. First step while you’re editing s
ettings.py, is to set
TIME_ZONE to your time zone. Note the
INSTALLED_APPS setting at the top of the file. That holds the names of all Django applications that are activated in this Django instance. Apps can be used in multiple projects, and you can package and distribute them for use by others in their projects. By default,
INSTALLED_APPS contains the following apps, all of which come with Django:
django.contrib.admin– The admin site.
django.contrib.auth– An authentication system.
django.contrib.contenttypes– A framework for content types.
django.contrib.sessions– A session framework.
django.contrib.messages– A messaging framework.
django.contrib.staticfiles– A framework for managing static files.
These applications are included by default as a convenience for the common case. Some of these applications makes use of at least one database table though, so we need to create the tables in the database before we can use them. To do that, run the following command:
migrate command looks at the
INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your
settings.py file and the database migrations shipped with the app (we’ll cover those later). You’ll see a message for each migration it applies.
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:
You’ll see the following output on the command line:
You’ve started the Django development server, a lightweight Web server written purely in Python. We’ve 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!