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
Download Django 9.6 from our software library for free. The most popular version of the tool 9.6. The actual developer of the software is Alain Veylit. Our built-in antivirus checked this download and rated it as 100% safe. The software belongs to Multimedia Tools. The size of the latest downloadable installation package is 2.2 MB. Is that Feasible to code in Python/Django? From uuid import getnode as getmac mac = getmac print mac The above code gives the MAC ID but this is my server's MAC ID. Is there any possible solution for that then please share. Thanks in Advance.
Django Download Media Files
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.
Download Django For Windows 10
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:
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).
Do Not Forget This Step!
It will solve most problems that arise from the incorrect mapping of pythonpath (an important variable for Python installations) in Windows.
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: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.
Terminal in Windows 10
If you are running newer versions of Windows 10, the command prompt has been replaced by PowerShell. For the examples in this book, the command prompt and PowerShell are functionally the same, and all commands will run in PowerShell unmodified.
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
On Mac
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:On a Mac, it’s:
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
On Mac
This will run the activate script inside your virtual environment’s
scripts
folder. You will notice your command prompt has now changed:On a Mac, the prompt looks like this:
The
(env_myclub)
at the beginning of the command prompt lets you know that you are running in the virtual environment.Oops! Script Error!
If you are using PowerShell and running this script for the first time, the
activate
command will throw a permission error.If this happens to you, open PowerShell as an administrator and run the command:
Once you have run this command, the activation script will run.
If you want to exit the virtual environment, you just type
deactivate
at the command prompt:Installing Django
Mac Users Note
Once Python 3 and the virtual environment are installed, the installation steps for Django are identical on both Windows and macOS.
The critical thing to remember with macOS is that system Python is version 2 and Django requires Python 3, so you must be running the Python virtual environment on macOS to run any of the code in this book.
Now we have Python installed and are running a virtual environment, installing Django is super easy, just type the command:
For Django 3, the command is:
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):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
: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:
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_myclubscriptsactivate
.From your virtual environment command line, run the following command:
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: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: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: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.
TIP: Remember the Startup Sequence
It will help to make a note of this sequence, so you know how to start your Django project each time you return to the examples in this book:
On Windows:
- Shift right-click your project folder to open a command window.
- Type in
env_myclubscriptsactivate
to run your virtual environment. - Change into your site directory (
cd myclub_site
) to runmanage.py
commands (e.g.,runserver
). - Type
deactivate
to exit the virtual environment.
On macOS:
- CTRL-click your project folder to open a terminal window.
- Type in
source env_myclub/bin/activate
to run your virtual environment. - Change into your site directory (
cd myclub_site
) to runmanage.py
commands (e.g.,runserver
). - Type
deactivate
to exit the virtual environment.
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.
This chapter covers how to properly configure your computer to work on Django projects. We start with an overview of the command line and how to install the latest version of Django and Python. Then we discuss virtual environments, git, and working with a text editor. By the end of this chapter you’ll be ready to create and modify new Django projects in just a few keystrokes.
The Command Line
The command line is a powerful, text-only view of your computer. As developers we will use it extensively throughout this book to install and configure each Django project.
On a Mac, the command line is found in a program called Terminal. To find it, open a new Finder window, open the Applications directory, scroll down to open the Utilities directory, and double-click the application called Terminal.
On Windows machines there are actually two built-in command shells: the Command shell and PowerShell. You should use PowerShell, which is the more powerful of the two.
Going forward when the book refers to the “command line” it means to open a new console on your computer, using either Terminal or PowerShell.
While there are many possible commands we can use, in practice there are six used most frequently in Django development:
cd
(change down a directory)cd ..
(change up a directory)ls
(list files in your current directory on Mac)dir
(list files in your current directory on Windows)pwd
(print working directory)mkdir
(make directory)touch
(create a new file on Mac)
Open your command line and try them out. The dollar sign (
$
) is our command line prompt: all commands in this book are intended to be typed after the $
prompt.For example, assuming you’re on a Mac, let’s change into our Desktop directory.
Note that our current location,
~/Desktop
, is automatically added before our command line prompt. To confirm we’re in the proper location we can use pwd
which will print out the path of our current directory.On my Mac computer this shows that I’m using the user
wsv
and on the desktop
for that account.Now let’s create a new directory with
mkdir
, cd
into it, and add a new file index.html
with the touch
command. Note that Windows machines unfortunately do not support a native touch
command. In future chapters when instructed to create a new file, do so within your text editor of choice.Now use
ls
to list all current files in our directory. You’ll see there’s just the newly created index.html
.As a final step, return to the Desktop directory with
cd ..
and use pwd
to confirm the location.Advanced developers can use their keyboard and command line to navigate through their computer with ease. With practice this approach is much faster than using a mouse.
In this book I’ll give you the exact instructions to run–you don’t need to be an expert on the command line–but over time it’s a good skill for any professional software developer to develop. A good free resource for further study is the Command Line Crash Course.
Install Python 3
It takes some configuration to properly install Python 3 on a Mac, Windows, Linux, or Chromebook computer and there are multiple approaches. Many developers–especially beginners–follow the advice on the official Python website to download distinct versions of Python directly onto their computer and then adjust the PATH variable accordingly.
The problem with this approach is that updating the PATH variable correctly is tricky, by downloading Python directly updates are harder to maintain, and there are now much easier ways to install and start using Python quickly.
I host a dedicated website, InstallPython3.com, with up-to-date guides for installing Python 3 on Mac, Windows, or Linux computers. Please refer there to install Python correctly on your local machine.
Virtual Environments
Virtual environments are an indispensable part of Python programming. They are an isolated container containing all the software dependencies for a given project. This is important because by default software like Python and Django is installed in the same directory. This causes a problem when you want to work on multiple projects on the same computer. What if ProjectA uses Django 3.1 but ProjectB from last year is still on Django 2.2? Without virtual environments this becomes very difficult; with virtual environments it’s no problem at all.
There are many areas of software development that are hotly debated, but using virtual environments for Python development is not one. You should use a dedicated virtual environment for each new Python project.
In this book we will use Pipenv to manage virtual environments. Pipenv is similar to
npm
and yarn
from the JavaScript/Node ecosystem: it creates a Pipfile
containing software dependencies and a Pipfile.lock
for ensuring deterministic builds. “Determinism” means that each and every time you download the software in a new virtual environment, you will have exactly the same configuration.Sebastian McKenzie, the creator of Yarn which first introduced this concept to JavaScript packaging, has a concise blog post explaining what determinism is and why it matters. The end result is that we will create a new virtual environment with
Pipenv
for each new Django Project.To install
Pipenv
we can use pip3
which Homebrew automatically installed for us alongside Python 3.Install Django
To see
Pipenv
in action, let’s create a new directory and install Django. First navigate to the Desktop, create a new directory django
, and enter it with cd
.Now use Pipenv to install Django. Note the use of
~=
which will ensure security updates for Django, such as 3.1.1, 3.1.2, and so on.If you look within our directory there are now two new files:
Pipfile
and Pipfile.lock
. We have the information we need for a new virtual environment but we have not activated it yet. Let’s do that with pipenv shell
.If you are on a Mac you should now see parentheses around the name of your current directory on your command line which indicates the virtual environment is activated. Since we’re in a
django
directory that means we should see (django)
at the beginning of the command line prompt. Windows users will not see the shell prompt. If you can run django-admin startproject
in the next section then you know your virtual environment has Django installed properly.This means it’s working! Create a new Django project called
config
with the following command. Don’t forget that period .
at the end.It’s worth pausing here to explain why you should add a period (
.
) to the command. If you just run django-admin startproject config
then by default Django will create this directory structure:See how it creates a new directory
config
and then within it a manage.py
file and a config
directory? That feels redundant to me since we already created and navigated into a django
directory on our Desktop. By running django-admin startproject config .
with the period at the end–which says, install in the current directory–the result is instead this:The takeaway is that it doesn’t really matter if you include the period or not at the end of the command, but I prefer to include the period and so that’s how we’ll do it in this book.
As you progress in your journey learning Django, you’ll start to bump up more and more into similar situations where there are different opinions within the Django community on the correct best practice. Django is eminently customizable, which is a great strength, however the tradeoff is that this flexibility comes at the cost of seeming complexity. Generally speaking it’s a good idea to research any such issues that arise, make a decision, and then stick with it!
Now let’s confirm everything is working by running Django’s local web server.
Don’t worry about the text in red about “18 unapplied migrations.” We’ll get to that shortly but the important part, for now, is to visit
http://127.0.0.1:8000/
and make sure the following image is visible:To stop our local server type
Control+c
. Then exit our virtual environment using the command exit
.We can always reactivate the virtual environment again using
pipenv shell
at any time.We’ll get lots of practice with virtual environments in this book so don’t worry if it’s a little confusing right now. The basic pattern is to install new packages with
pipenv
, activate them with pipenv shell
, and then exit
when done.It’s worth noting that only one virtual environment can be active in a command line tab at a time. In future chapters we will be creating a brand new virtual environment for each new project so either make sure to
exit
your current environment or open up a new tab for new projects.Install Git
Git is an indispensable part of modern software development. It is a version control system which can be thought of as an extremely powerful version of track changes in Microsoft Word or Google Docs. With git, you can collaborate with other developers, track all your work via commits, and revert to any previous version of your code even if you accidentally delete something important!
On a Mac, because HomeBrew is already installed we can simply type
brew install git
on the command line:On Windows you should download Git from Git for Windows. Click the “Download” button and follow the prompts for installation.
Once installed, we need to do a one-time system set up to configure it by declaring the name and email address you want associated with all your Git commits. Within the command line console type the following two lines. Make sure to update them your name and email address.
You can always change these configs later if you desire by retyping the same commands with a new name or email address.
Text Editors
The final step is our text editor. While the command line is where we execute commands for our programs, a text editor is where the actual code is written. The computer doesn’t care what text editor you use–the end result is just code–but a good text editor can provide helpful hints and catch typos for you.
Experienced developers often prefer using either Vim or Emacs, both decades-old, text-only editors with loyal followings. However each has a steep learning curve and requires memorizing many different keystroke combinations. I don’t recommend them for newcomers.
Modern text editors combine the same powerful features with an appealing visual interface. My current favorite is Visual Studio Code which is free, easy to install, and enjoys widespread popularity. If you’re not already using a text editor, download and install Visual Studio Code now.
Conclusion
Phew! Nobody really likes configuring a local development environment but fortunately it’s a one-time pain. We have now learned how to work with virtual environments and installed the latest version of Python and git. Everything is ready for our first Django app.
Continue on to Chapter 2: Hello World app.