Before you can start learning Django, you must install some software on your computer. Fortunately, this is a simple three-step process:
- Install Python
- Install a Python Virtual Environment; and
- Install Django
I’ve written this chapter mostly for those of you running Windows, as most new users are on Windows. I have also included a section on installing Python 3 and Django on macOS. If you are using Linux, there are many resources on the Internet—the best place to start is 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 use the development server and SQLite to run all the code in this book. This is by far the easiest and best way to set up Django when you are first starting.
Installing Python
A lot of Windows applications use Python, so it may be already installed on your system. You can check this out by opening a command prompt, or running PowerShell, and typing python
at the prompt.
If Python isn’t installed you’ll get a message saying that Windows can’t find Python. If Python is installed, the python command will open the Python interactive interpreter:
C:\Users\Nigel>python
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 can see in the above example that my PC is running Python 3.6.0. Django 2.2 is compatible with Python version 3.5 and later. Django 3.0 is compatible with Python version 3.6 and later. If you have an older version of Python, you must install Python 3.7 or 3.8 for the code in this book to work. If you have Python 3.5 or 3.6, I still recommend you install Python 3.8 to ensure you have the latest version installed on your machine.
Assuming Python 3 is not installed on your system, you first need to get the installer. Go to https://www.python.org/downloads/ and click the big yellow button that says “Download Python 3.8.x”.
At the time of writing, the latest version of Python is 3.8.3, but it may have been updated by the time you read this, so the numbers may be slightly different. 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 essential customization you must make.
By default, the Python executable is not added to the Windows PATH. For Django to work correctly, 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.8 to PATH” is checked before installing (Figure 2-1).
Figure 2.1: Check the “Add Python 3.8 to PATH” box before installing.
Once Python is installed, restart Windows and then type python
at the command prompt. You should see something like this:
C:\Users\nigel> python
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Installing Python on macOS
If you open a terminal and type python
at the prompt, you will see that the system version is Python 2 (Figure 2-2). Django is not compatible with Python 2, so we need to install the latest version of Python 3.
Figure 2-2: macOS uses Python 2, which is incompatible with Django.
Downloading a copy of Python 3 follows the same process as Windows—Go to https://www.python.org/downloads/ and click the big yellow button that says “Download Python 3.x.x”. Your browser should automatically detect that you are using macOS and take you to the correct download page. If it doesn’t, select the correct operating system from the links below the button.
The Mac installer is in .pkg
format, so once it’s downloaded, double-click the file to run the package installer (Figure 2-3). The screenshot is for Python 3.7, but the process is identical for Python 3.8.
Figure 2-3: Follow the prompts to install Python 3 on macOS.
Follow the installations steps and, when Python 3 has been installed, open a new terminal window. If the installation was successful, typing python3
at the prompt will open the Python 3 interactive shell (Figure 2-4). Note that macOS will happily run multiple versions of Python on the one machine, you just need to make sure you select the correct version when running the terminal.
Figure 2-4: Once Python 3 is installed, run it from the terminal with the python3
command.
Creating a Python Virtual Environment
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 many 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 filesystem separate from the rest of the software on your computer.
The virtual environment tool in Python is called venv
, but before we set up venv
, we need to create our club site project folder.
Create a Project Folder
Our project folder will house not only our virtual environment, but all the code and media for our Django club site.
The project folder can go anywhere on your computer, although it’s highly recommended you create it somewhere in your user directory, so you don’t get permission issues later on. A good place for your project in Windows is your My Documents folder. On a Mac your Documents folder is also a logical choice; however, it can go anywhere in your user directory.
Create a new folder on your system. I have named the folder myclub_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 macOS). The easiest way to do this in 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 2-5).
Figure 2.5: Hold the shift key and right-click a folder to open a command window.
Create a Python Virtual Environment
Once you have created your project folder, you need to create a virtual environment for your project by typing the following at the command prompt you just opened:
On Windows
...\Documents\myclub_project> python -m venv env_myclub
On Mac
...$ python3 -m venv env_myclub
Remember, you must be inside the project folder!
The function of this command is straightforward—the -m
option tells Python to run the venv
module as a script. venv
in turn requires one parameter: the name of the virtual environment to be created. So this command is saying “create a new Python virtual environment and call it env_myclub”
Once venv
has finished setting up your new virtual environment, it will switch to an empty command prompt. When it’s done, open Windows Explorer and have a look at what venv
created for you. In your project folder, you will now see a folder called \env_myclub
(or whatever name you gave the virtual environment). If you open the folder on Windows, you will see the following:
\Include
\Lib
\Scripts
pyvenv.cfg
On a Mac, it’s:
/bin
/Include
/Lib
pyvenv.cfg
On either platform, if you look inside the \Lib
folder, you will see venv
has created a complete Python installation for you, separate from your other software, so you can work on your project without affecting other software on your 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:
On Windows
env_myclub\scripts\activate
On Mac
source env_myclub/bin/activate
This will run the activate script inside your virtual environment’s \scripts
folder. You will notice your command prompt has now changed:
(env_myclub) ...\Documents\myclub_project>
On a Mac, the prompt looks like this:
(env_myclub) ... <yourusername>$
The (env_myclub)
at the beginning of the command prompt lets you know that you are running in the virtual environment.
If you want to exit the virtual environment, you just type deactivate
at the command prompt:
(env_myclub) ...\Documents\myclub_project> deactivate
...\Documents\myclub_project>
Installing Django
Now we have Python installed and are running a virtual environment, installing Django is super easy, just type the command:
pip install "django>=2.2,<3"
For Django 3, the command is:
pip install "django>=3.0,<4"
If you are not familiar with the pip
command, put briefly, it’s the Python package manager and is used to install Python packages. To keep with Python programming tradition, pip
is a recursive acronym for “Pip Installs Packages”.
This will instruct pip
to install the latest version of Django 2 or Django 3 into your virtual environment. Your command output should look like this (for Django 2.2):
(env_myclub) ...\myclub_project> pip install "django>=2.2,<3.0"
Collecting django<3.0,>=2.2
Downloading .../Django-2.2.12-py3-none-any.whl (7.5MB)
|################################| 7.5MB 2.2MB/s
Collecting pytz (from django<3.0,>=2.2)
Downloading .../pytz-2020.1-py2.py3-none-any.whl (510kB)
|################################| 512kB 3.3MB/s
Collecting sqlparse (from django<3.0,>=2.2)
Downloading .../sqlparse-0.3.1-py2.py3-none-any.whl (40kB)
|################################| 40kB 2.6MB/s
Installing collected packages: pytz, sqlparse, django
Successfully installed django-2.2.12 pytz-2020.1 sqlparse-0.3.1
The Django 3 installation output is identical except for the version numbers.
To test the installation, go to 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_myclub) ...\myclub_project>python
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.get_version()
'2.2.12' # Your version may be different.
>>> exit()
Don’t forget to exit the Python interpreter when you are done (you can also use CTRL-Z).
You can also check if Django has been installed directly from the command prompt with:
(env_myclub) ...\myclub_project>python -m django --version
2.2.12 # Your version may be different.
Starting a Project
Once you’ve installed Python and Django, you can take the first step in developing a Django application by creating a Django project.
A Django project is a collection of settings and files for a single Django website. To create a new Django project, we’ll be using a special command to auto-generate the folders, files and code that make up a Django project. This includes a collection of settings for an instance of Django, database configuration, Django-specific options and application-specific settings.
I am assuming you are still running the virtual environment from the previous installation step. If not, start it again with env_myclub\scripts\activate\
.
From your virtual environment command line, run the following command:
(env_myclub) ...\myclub_project>django-admin startproject myclub_site
This command will automatically create a myclub_site
folder in your project folder, and all the necessary files for a basic, but fully functioning Django website. Feel free to explore what startproject
created now if you wish, however, we will go into greater detail on the structure of a Django project in the next chapter.
Creating a Database
Django includes several 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 the project database before we can use them. To do this, change into the myclub_site
folder created in the last step (type cd myclub_site
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). If all goes to plan, you’ll see a message for each migration it applies:
(env_myclub) ...\myclub_site>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. Make sure you are in the outer myclub_site
directory and run the following command:
python manage.py runserver
This will start the Django development server—a lightweight Web server written in Python. The development server was created so you can develop things rapidly, without having to deal with configuring a production server until you’re ready for deployment.
When the server starts, Django will output a few messages before telling you that the development server is up and running at http://127.0.0.1:8000/
. If you were wondering, 127.0.0.1 is the IP address for localhost, or your local computer. The 8000 on the end is telling you that Django is listening at port 8000 on your local host.
You can change the port number if you want to, but I have never found a good reason to change it, so best to keep it simple and leave it at the default.
Now that the server is running, visit http://127.0.0.1:8000/
with your web browser. You’ll see Django’s default welcome page, complete with a cool animated rocket (Figure 2-6).
It worked!
Figure 2.6: Django’s welcome page. The welcome page is the same for Django 2 and 3.
Chapter Summary
In this chapter, I showed you how to install Python 3 and Django on both Windows and macOS. In the next chapter, we will step back a bit and have a big-picture look at Django’s structure and how all the parts of Django work together to create powerful, scalable web applications.
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.