This chapter focuses on configuring your Windows or macOS computer to work on Django projects. You are probably eager to dive right in, but setting up your computer now is a one-time pain that will pay dividends.

Before installing Django, we must look at the Command Line, a powerful text-only interface developers use extensively. Next, we will install the latest version of Python, learn how to create dedicated virtual environments, and install Django. As a final step, we will explore using Git for version control and working with a text editor. By the end of this chapter, you will have created your first Django project from scratch and be able to create and modify new Django projects with just a few keystrokes.

The Command Line

The command line is a text-only interface that harkens back to the original days of computing. If you have ever seen a television show or movie where a hacker is furiously typing into a black window: that’s the command line. It is an alternative to the mouse or finger-based graphical user interface familiar to most computer users. Regular computer users will never need to use the command line. Still, for software developers, it is a vital and regularly-used tool necessary to execute programs, install software, use Git for version control, and connect to servers in the cloud. With practice, most developers find that the command line is a faster and more powerful way to navigate and control a computer.

Given its minimal user interface–just a blank screen and a blinking cursor–the command line is intimidating to newcomers. There is often no feedback after a command has run, and it is possible to wipe the contents of an entire computer with a single command if you’re not careful: no warning will pop up! As a result, use the command line with caution. Do not blindly copy and paste commands you find online blindly; rely only on trusted resources.

In everyday usage, multiple terms are used to refer to the command line: Command Line Interface (CLI), console, terminal, shell, or prompt. Technically speaking, the terminal is the program that opens up a new window to access the command line, a console is a text-based application, and the shell is the program that runs commands on the underlying operating system. The prompt is where commands are typed and run. It is easy to be confused by these terms initially, but they all essentially mean the same thing: the command line is where we run and execute text-only commands on our computer.

The built-in terminal and shell on Windows are both called PowerShell. To access it, locate the taskbar next to the Windows button on the bottom of the screen and type in “PowerShell” to launch the app. It will open a new window with a dark blue background and a blinking cursor after the > prompt. Here is how it looks on my computer.

PS C:\Users\wsv>

Before the prompt is PS, which refers to PowerShell, the initial C directory of the Windows operating system, followed by the Users directory and the current user, which on my personal computer, is wsv. Your username will be different. Don’t worry about what comes to the left of the > prompt at this point: it varies depending on each computer and can be customized later. The shorter prompt of > will be used going forward for Windows.

On macOS, the built-in terminal is called, appropriately enough, Terminal. Open it via the Spotlight app: simultaneously press the Command and space bar keys and then type in “terminal.” Alternatively, open a new Finder window, navigate to the Applications directory, scroll down to open the Utilities directory, and double-click the Terminal application, which opens a new screen with a white background by default and a blinking cursor after the % prompt. Don’t worry about what comes to the left of the % prompt. It varies by computer and can be customized later on.

Wills-Macbook-Pro:~ wsv%

The default shell for macOS since 2019 is zsh, which uses the % prompt. If you see $ as your prompt, then you are using the previous default macOS shell, Bash. While most of the commands in this book will work interchangeably, it is recommended to look online at how to change to zsh via System Preferences if your computer still uses Bash.

Note: In this book, we will use the universal $ Unix prompt for all shell commands rather than alternating between > on Windows and % on macOS.

Shell Commands

There are many available shell commands, but developers generally rely on half a dozen commands for day-to-day use and look up more complicated commands as needed.

In most cases, Windows (PowerShell) and macOS commands are similar. For example, the command whoami returns the computer name/username on Windows and the username on macOS. As with all shell commands, type the command itself followed by the return key. Note that the # symbol represents a comment; these are not executed on the command line.

# Windows
$ whoami
wsv2023/wsv

# macOS
$ whoami
wsv

Sometimes, however, the shell commands on Windows and macOS are entirely different. A good example is the command for outputting a basic “Hello, World” message to the console. On Windows, the command is Write-Host, while on macOS, it is echo.

# Windows
$ Write-Host "Hello, World"
Hello, World

# macOS
$ echo "Hello, World"
Hello, World

A frequent task on the command line is navigating within the computer filesystem. On Windows and macOS, the command pwd (print working directory) outputs the current location within the file system.

# Windows
$ pwd

Path
----
C:\Users\wsv

# macOS
$ pwd
/Users/wsv

You can save your Django code anywhere, but we will place our code in the desktop directory for convenience. The command cd (change directory) followed by the intended location works on both systems.

# Windows
$ cd onedrive\desktop
$ pwd

Path
----
C:\Users\wsv\onedrive\desktop

# macOS
$ cd desktop
$ pwd
/Users/wsv/desktop

Tip: The tab key will autocomplete a command, so if you type cd d and then hit tab, it will automatically fill in the rest of the name. If more than two directories start with d, hit the tab key again to cycle through them.

To make a new directory, use the command mkdir followed by the name. We will create one called code on the desktop and a new directory within it, ch1-setup.

# Windows
$ mkdir code
$ cd code
$ mkdir ch1-setup
$ cd ch1-setup

# macOS
$ mkdir code
$ cd code
$ mkdir ch1-setup
$ cd ch1-setup

You can check that it has been created by looking on your desktop or running the command pwd.

# Windows
$ pwd

Path
----
C:\Users\wsv\onedrive\desktop\code\ch1-setup

# macOS
$ pwd
/Users/wsv/desktop/code/ch1-setup

Tip: The clear command will clear the terminal of past commands and outputs, so you have a clean slate. The tab command autocompletes the line, as we’ve discussed. And the and keys cycle through previous commands to save yourself from typing the same thing over and over again.

To exit, you could close the terminal with your mouse, but the hacker way is to use the shell command exit instead, which works by default on Windows; on macOS, the Terminal preferences need to be changed. Click Terminal at the top of the screen, then Preferences from the dropdown menu. Click on Profiles in the top menu and then Shell from the list below. There is a radio button for “When the shell exits.” Select “Close the window.”

$ exit

With practice, the command line is a far more efficient way to navigate and operate your computer than a mouse. You don’t need to be a command line expert to complete this book: I will provide the exact instructions to run each time. But if you are curious, a complete list of shell commands for each operating system is available at ss64.com.

Install Python 3 on Windows

On Windows, Microsoft hosts a community release of Python 3 in the Microsoft Store. In the search bar at the bottom of your screen, type in “python” and click on the best match result, automatically launching Python 3.11 on the Microsoft Store. Click on the blue “Get” button to download it.

To confirm Python is installed correctly, open a new Terminal window with PowerShell and then type python --version.

$ python --version
Python 3.11.2

The result should be at least Python 3.11. Then type python to open the Python interpreter from the command line shell.

$ python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 2 2023, 16:38:35)
  [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits", or "license" for more information.
>>>

Install Python 3 on Mac

On Mac, the official installer on the Python website is the best approach. In a new browser window, go to the Python downloads page and click on the button underneath the text “Download the latest version for Mac OS X.” As of this writing, that is Python 3.11. The package will be in your Downloads directory: double-click on it to launch the Python Installer, and follow the prompts.

To confirm the download was successful, open a new Terminal window and type python3 --version.

$ python3 --version
Python 3.11.2

Then type python3 to open the Python interpreter.

$ python3
Python 3.11.2 (v3.11.2:878ead1ac1, Feb  7 2023, 10:02:41)
  [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python Interactive Mode

From the command line, type either python on Windows or python3 on macOS to bring up the Python Interpreter, also known as Python Interactive mode. The new prompt of >>> indicates that you are now inside Python itself and not the command line. If you try any previous shell commands we ran–cd, ls, mkdir–they will raise errors. What will work is actual Python code. For example, try out both 1 + 1 and print("Hello Python!") making sure to hit the Enter or Return key after each to run them.

>>> 1 + 1
2
>>> print("Hello Python!")
Hello Python!

Python’s interactive mode is a great way to save time if you want to try out a short bit of Python code. But it has several limitations: you can’t save your work in a file, and writing longer code snippets is cumbersome. As a result, we will spend most of our time writing Python and Django in files using a text editor.

To exit Python from the command line, type either exit() and the Enter key or use Ctrl + z on Windows or Ctrl + d on macOS.

Virtual Environments

Installing the latest version of Python and Django is the correct approach for any new project. But in the real world, it is common that existing projects rely on older versions of each. Consider the following situation: Project A uses Django 3.2, but Project B uses Django 4.2. By default, Python and Django are installed globally on a computer: installing and reinstalling different versions every time you want to switch between projects is quite a pain.

Fortunately, there is a straightforward solution. Virtual environments allow you to create and manage separate environments for each Python project on the same computer. Many areas of software development are hotly debated, but using virtual environments for Python development is not. You should use a dedicated virtual environment for each new Python and Django project.

There are several ways to implement virtual environments, but the simplest is with the venv module already installed as part of the Python 3 standard library. To try it out, navigate to your desktop’s existing ch1-setup directory.

# Windows
$ cd onedrive\desktop\code\ch1-setup

# macOS
$ cd ~/desktop/code/ch1-setup

To create a virtual environment within this new directory, use the format python -m venv <name_of_env> on Windows or python3 -m venv <name_of_env> on macOS. The -m part of this command is known as a flag, which is a convention to indicate the user is requesting non-default behavior. The format is usually - and then a letter or combination of letters. The -m flag is necessary since venv is a module name. It is up to the developer to choose a proper environment name, but a common choice is to call it .venv, as we do here.

# Windows
$ python -m venv .venv

# macOS
$ python3 -m venv .venv

On Windows, the command ls will display the .venv directory in our directory. However, on macOS using ls it will appear empty. The .venv directory is there; it’s just that it is “hidden” due to the period . that precedes the name. Hidden files and directories are a way for developers to indicate that the contents are important and should be treated differently than regular files. To view it, try ls -la, which shows all directories and files, even hidden ones.

> ls -la
total 0
drwxr-xr-x  3 wsv  staff   96 Dec  12 11:10 .
drwxr-xr-x  3 wsv  staff   96 Dec  12 11:10 ..
drwxr-xr-x  6 wsv  staff  192 Dec  12 11:10 .venv

You will see that .venv is there and can be accessed via cd if desired. In the directory is a copy of the Python interpreter and a few management scripts, but you will not need to use it directly in this book.

Once created, a virtual environment must be activated. On Windows, an Execution Policy must be set to enable running scripts. You only have to do this once to tell Windows that, I know what I’m doing here. The Python docs recommend allowing scripts for the CurrentUser only, which is what we will do. On macOS, there are no similar restrictions on scripts, so it is possible to run source .venv/bin/activate directly.

Here is what the complete commands look like to create and activate a new virtual environment called .venv:

# Windows
$ python -m venv .venv
$ Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
$ .venv\Scripts\Activate.ps1
(.venv) $

# macOS
$ python3 -m venv .venv
$ source .venv/bin/activate
(.venv) $

The shell prompt now has the environment name (.venv) prefixed, which indicates that the virtual environment is active. Any future Python packages installed or updated within this location will be confined to the active virtual environment.

To deactivate and leave a virtual environment, type deactivate.

(.venv) $ deactivate
$

The shell prompt no longer has the virtual environment name prefixed, which means the session is now back to normal.

PyPI (Python Package Index)

PyPI (Python Package Index) is the central location for all Python projects. You can see Django is there along with every other Python package we will use in this book.

We will use pip, the most popular package installer, to install Python packages. It already comes included with Python 3, but to ensure we are on the latest version of pip, let’s take a moment to update it. Here is the command to run:

$ python -m pip install --upgrade pip

This command will install and upgrade (if needed) the latest version of pip. Notice that we are not in a virtual environment, so this version of pip will be installed globally on our local computer.

Why do we use python -m pip instead of just pip for this command? The latter does work, but it can cause some issues. Using python with the -m flag ensures that the intended version of Python is in use, even if you have multiple versions of Python installed on your computer. For example, if you have Python 2.7 and 3.7 installed on your computer, it is possible for pip install to use Python 2.7 at one point but Python 3.7 later: not desired behavior. Brett Cannon has a much fuller explanation if you are curious about the underlying reasons why this is the case.

Python is now installed, we know how to use virtual environments, and we’ve updated our version of pip. It is time to install Django itself for the first time.

Install Django

In the ch1-setup directory, reactivate the existing virtual environment and install Django.

# Windows
$ .venv\Scripts\Activate.ps1
(.venv) $ python -m pip install django~=4.2.0

# macOS
$ source .venv/bin/activate
(.venv) $ python3 -m pip install django~=4.2.0

This command uses the comparison operator, ~=, to install the latest version of Django 4.2.x. As I type these words, the newest version is 4.2.0, but soon it will be 4.2.1 and then a month later 4.2.2. By using ~=4.2.0, we ensure that the latest version of 4.2.x will be installed when the user executes the command.

If we did not “pin” our version number in this way–if we just installed Django using the command python -m pip install django–then the latest version of Django will be installed even if, in the future, it is 5.0 or 5.1 or even 6.0. There is no guarantee that all the code in this book will work perfectly on a later version of Django. By specifying the version number for each software package installed, you can update them one at a time to ensure compatibility.

Note: I will provide Windows and macOS commands throughout this book if they differ. However, when it comes to using python on Windows vs. python3 on macOS, the default will be python for conciseness.

First Django Project

To create a new Django project, use the command django-admin startproject django_project . A Django project can have almost any name, but we will use django_project in this book.

(.venv) $ django-admin startproject django_project .

It’s worth pausing here to explain why you should add a period (.) to the end of the previous command. If you just run django-admin startproject django_project, then by default Django will create this directory structure:

django_project/
    ├── django_project
    │   ├── __init__.py
    │   ├── asgi.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    ├── manage.py
    └── .venv/

Do you see the multiple django_project directories? First, a top-level django_project directory is created, and then another one within it that contains the files we need for our Django project. Opinions differ on the “best” approach within the Django community, but it feels redundant to me to have these two directories with the same name and makes deployment easier later on, so I prefer adding a period to the end that installs Django in the current directory.

├── django_project
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── .venv/

As you progress in your journey learning Django, you will 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, make a decision, and then stick with it!

The Development Server

Django includes a built-in, lightweight Web server for local development that is accessible via the runserver command. The development server automatically reloads Python code for each request so you don’t need to restart the server for code changes to take effect. Be aware, however, that some actions like adding files will not automatically trigger a restart so if your code is not working as expected, doing a manual restart is always a good first step.

By default, the server runs on port 8000 on the IP address 127.0.0.1, which is known as the “loopback address” because no data is actually sent from our computer (host) to the local network or internet; instead, it is “looped back” on itself so the computer sending the data becomes the recipient.

Let’s confirm everything is working correctly by starting up the development server now. We’ll use manage.py to execute the runserver command.

(.venv) $ python manage.py runserver

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 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.
April 13, 2023 - 13:15:03
Django version 4.2, using settings 'django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-BREAK.

Don’t worry about the text in red about 18 unapplied migrations. We’ll get to that shortly. The important part, for now, is to visit http://127.0.0.1:8000/ in your web browser and make sure the following image is visible:

Django welcome page

If you are on Windows, you will see the final line says to use CONTROL-BREAK to quit, whereas on macOS, it is CONTROL-C. Newer Windows keyboards often do not have a Pause/Break key so using the c key usually works.

Resist the temptation to use the development server for production. It can handle only a single request at a time reliably and has not undergone any security audits or performance tests. There are dedicated web servers for that sort of thing that we will use in later chapters.

If you want to change the port number you can do so by passing in a command-line argument. For example, you could stop the server and then restart it on port 8080.

(.venv) $ python manage.py runserver 8080

Generally speaking, Django developers don’t need to do this but as will become a running theme in this book, Django provides ultimately flexibility if needed.

For readers new to web development, be aware that is it also possible to visit http://localhost:8000/ to see the running Django website. localhost is a common shortand for 127.0.0.1. In this book we will default to 127.0.0.1:8000 because that is what Django outputs in the terminal but either option is fine.

Go ahead and stop the local server with the appropriate command and then exit the virtual environment by typing deactivate and hit Return.

# Windows or macOS
(.venv) $ deactivate

We’ll get lots of practice with virtual environments in this book, so don’t worry if it’s a little confusing. The basic pattern for any new Django project is to make and activate a virtual environment, install Django, and then run startproject.

It’s worth noting that only one virtual environment can be active in a command line tab. In future chapters, we will create a new virtual environment for each new project, so either make sure to deactivate your current environment or open up a new tab for new projects.

Text Editors

The command line is where we execute commands for our programs, but a text editor is where the code is actually written. The computer doesn’t care what text editor you use–the result is just code–but a good text editor can provide helpful hints and catch typos for you.

Many modern text editors are available that come with helpful extensions to make Python and Django development more accessible. PyCharm is a very popular option that has both a paid Professional and free Community version. Visual Studio Code is also free, easy to install, and enjoys widespread popularity. It does not matter what text editor you decide to use: the result is just code.

VSCode Configurations

If you’re not already using a text editor, download and install VSCode from the official website. There are three recommended configurations you can add to improve your developer productivity.

The first is to add the official Python extension to VSCode. On Windows, navigate to File -> Settings -> Extensions; on macOS, Code -> Settings -> Extensions to launch a search bar for the extensions marketplace. Enter “python” to bring up the Microsoft extension as the first result. Install it.

The second is adding Black, a Python code formatter that has quickly become the default within the Python community. In the terminal run the command python -m pip install black on Windows or python3 -m pip install black on macOS.

(.venv) $ python -m pip install black 

Next, within VSCode open up the settings by navigating to File -> Preferences -> Settings on Windows or Code -> Preferences -> Settings on macOS. Search for “python formatting provider” and select black from the dropdown options. Then search for “format on save” and enable “Editor: Format on Save”. Black will automatically format your code whenever a *.py file is saved.

To confirm this is working, use your text editor to create and save a new file called hello.py within the ch1-setup directory located on your desktop and type in the following using single quotes:

print('Hello, World!')

On save, it should update automatically to using double quotes, which is Black’s default preference: print("Hello, World!"). That means everything is working correctly.

The third configuration makes it possible to open VSCode from your terminal. This is quite useful since a standard workflow will be to open up the terminal, navigate to a directory you want to work on, and then open it with VSCode.

Within VSCode simultaneously press Command + Shift + P to open the command palette, which allows us to customize our VS Code settings. In the command palette type shell: the top result will be “Shell Command: Install code command in PATH.” Then hit enter to install this shortcut. There will be a success message saying “Shell command ‘code’ successfully installed in PATH.” The PATH variable, by the way, is often used to customize terminal prompts.

Now go back to your terminal and navigate to the ch1-setup directory. If you type code . it will open up in VS Code.

(.venv) $ code .

Install Git

The final step is to install Git, a version control system indispensable to modern software development. 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! This is not a book on Git, so all necessary commands are given and briefly explained, but there are numerous resources available for free on the internet if you’d like to learn more about Git itself.

On Windows, navigate to the official website at https://git-scm.com/ and click on the “Download” link, which should install the proper version for your computer. Save the file, open your Downloads folder, and double-click on the file to launch the Git for Windows installer. Click the “Next” button through most early defaults as they are fine and can always be updated later. Make sure that under “Choosing the default editor used by Git”, the selection is for “Use Visual Studio Codeas Git’s default editor.” And in the section on “Adjusting the name of the initial branch in new repositories,” make sure the option to “Override the default branch name for new repositories” is selected so that “main” is used.

To confirm Git is installed on Windows, close all current shell windows and then open a new one which will load the changes to our PATH variable. Type in git --version to display the installed version of Git.

# Windows
$ git --version
git version 2.39.1.windows.1

On macOS, Xcode is primarily designed for building iOS apps but includes many developer features needed on macOS. Currently, installing Git via Xcode is the easiest option. To check if Git is installed on your computer, type git --version in a new terminal window.

# macOS
$ git --version

If you do not have Git installed, a popup message will ask if you want to install it as part of “command line developer tools.” Select “Install” which will load Xcode and its command line tools package. Or if you do not see the message, type xcode-select --install instead to install Xcode directly.

Be aware that Xcode is a very large package, so the initial download may take some time. Xcode is primarily designed for building iOS apps and also includes many developer features needed on macOS. Once the download is complete, close all existing terminal shells, open a new window, and type in git --version to confirm the install worked.

# macOS
$ git --version
git version 2.37.1 (Apple Git-137.1)

Once Git installs on your local machine, we need to do a one-time system configuration by declaring the name and email address associated with all your Git commits. We will also set the default branch name to main. Within the command line shell, type the following two lines. Make sure to update them with your name and email address, not the defaults of “Your Name” and “[email protected]”!

$ git config --global user.name "Your Name"
$ git config --global user.email "[email protected]"
$ git config --global init.defaultBranch main

If you desire, you can always change these configs later by retyping the same commands with a new name or email address.

Conclusion

It is a challenging task to configure a software development environment from scratch. Even experienced programmers have difficulty with the job, but it is a one-time pain that is more than worth it. We know have the ability to start up new Django projects quickly and have learned about the command line, Python interactive mode, how to install the latest version of Python and Django, configured our text editor, and installed Git. Everything is ready for our first proper Django website in the next chapter.

Continue on to Chapter 2: Hello World app.