Install Django


There are various ways to install the Django framework. The list of Django installation options including their pros and cons is presented in Table 1-1.

Table 1-1. Django installation options - Pros and Cons

ApproachHow to get Django Pros Cons
From pip Python package manager, via pip install (Recommended option) Resolution and download through network. Allows install on virtual Python environment.
Dependencies are taken care of automatically.
Latest version may not be available.
Needs network connection.
Dealing with package internals (e.g. wheel) can be difficult, although it's rarely required.
Download from main site as tar.gz file[7]. Easy access to latest Django stable release.
Requires no network connection.
Requires manual download and install.
Download from Git[8]. Access to the latest Django features. Can contain bugs.
From operating system (OS) package manager (e.g. apt, rpm) Resolution and download through network. Easy to install.
Dependencies are taken care of automatically.
Automatic updates
Latest version may not be available.
Installed on global Python environment.
From Python's PYTHONPATH environment variable Download from main site as tar.gz file[7]. Easiest access to latest Django stable release.
Requires no network connection.
Requires manual download and install.
Keeping track of PYTHONPATH on different envioronments.
Download from Git[8]. Access to the latest Django features.
Quickest way to modify/update core parts of Django.
Can contain bugs.
Keeping track of PYTHONPATH on different envioronments.

As emphasized in table 1-1, the recommended option to install Django is to use the Python pip package manager because it provides the most flexibility. Next, I'll describe each of the steps to install Django using this approach and more importantly how to get up and running with pip.

Once you're familiar with pip and the various ways it can install Django, I'll then describe the other alternatives to install Django, which includes using an operating system (OS) package manager, as well as Python's PYTHONPATH environment variable.

Install Python (Pre-requisite)

Since Django is built on Python, you first need to install Python to run Django. The latest Django release is version 4.0, Django 4.0 requires that you either have a Python 3.8 or higher release (3.9 or 3.10).

If you use a Unix/Linux OS, Python is very likely installed on your system. If you type which python on a Unix/Linux terminal and it returns a response (e.g. /usr/bin/python) it indicates the location of the Python executable, if there is no response it indicates the Python executable is not available on the system.

If you don't have Python on your system and you're using a Debian or Ubuntu Linux distribution, you can use the OS package manager apt to install Python by typing: apt install python. If you have a Unix/Linux distribution that is not Debian or Ubuntu and you need to install Python, consult your Unix/Linux documentation for available Python packages or download the Python sources from http://python.org/download/ to do the installation.

If you have a system that runs on a Windows OS or macOS, Python installers are available for download from http://python.org/download/.

Irrespective of your system's OS, once you've finished the Python installation, ensure Python 3 is installed correctly and accessible from anywhere on your system. Open a terminal and type python, python3 or inclusively python3.8, python3.9 or python3.10 -- these variations depend on how you installed Python or if you have multiple Python versions on the same system. In either scenario, you should enter a Python interactive session like the one illustrated in listing 1-1.

Listing 1-1 - Python interactive session

[user@~]$ python3
Python 3.9.10 (main, Jan 15 2022, 18:17:56) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

If you aren't able to enter a Python interactive session that explicitly indicates Python 3.8, Python 3.9 or Python 3.10, review the Python installation process because you will not be able to continue with the following sections.

Install (or verify & update) pip package manager (Pre-requisite)

To make Python package installation and management easier, Python uses a package manager called pip. Most Python distributions include the pip executable and just like the python executable, will be named either pip3, pip3.8, pip3.9 or pip3.10, depending on the underlying Python version. Now let's verify and update pip on your system as shown in listing 1-2, if you don't have pip on your system, I'll provide instructions on how to install pip right after listing 1-2.

Listing 1-2. Verify & update pip package manager

[user@~]$ python3 -m pip --version
pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.9)
[user@~]$ python3 -m pip install --upgrade pip
Collecting pip
  Using cached pip-22.0.2-py3-none-any.whl (2.1 MB)
Installing collected packages: pip
Successfully installed pip-22.0.2

The first step in listing 1-2 uses the python3 executable alias with the standard Python -m flag to invoke pip and get its version. You can see the output indicates a working pip 20.0.2 version used by the python 3.9 version, which is accessible through the python3 executable alias. In this case, the non-alias equivalent command python3.9 -m pip --version would also output the same result as python3 -m pip --version.

If you see an error like The program 'pip' is currently not installed, pip not found or No module named pip, it means your Python installation is not equipped with pip. In this case, you'll need to install the pip executable directly, by either:

Once the pip executable is installed, run the pip version check from the first line in listing 1-2 to ensure pip is installed.

Next, listing 1-2 shows the update process for pip that uses the same python3 -m (or python3.9 -m) command with the arguments install --upgrade pip, where install is the pip installation command and --upgrade pip indicates that installation be an upgrade for pip itself. Upon execution, pip searches for the most recent release of the package with the provided name -- in this case pip itself -- downloads it and performs an upgrade in case it isn't already installed.

Tip There are many other pip commands and flags to manage packages. To get a full list use:

  • The Python 3 executable alias command: python3 -m pip --help.
  • Or the Python executable command your choice: python3.9 -m pip --help for Python 3.9.

With pip on your system, you're ready to move on to the next step.

Install virtualenv (Optional pre-requisite)

Virtualenv is not essential to develop Django applications, but I highly recommend you use it because it allows you to create virtual Python environments on a single system. By using virtual Python environments, applications can run in their own 'sandbox' in isolation of other Python applications. Initially virtualenv can appear to be of little benefit, but it can be of tremendous help for tasks like replicating a development environment to a production environment and avoiding version conflicts that can arise between different applications.

Without virtualenv you can still proceed to install Django and any other Python package using pip, but the issue is all packages are installed under the global Python installation. Initially this can seem convenient, because you only need to install packages once in the global Python installation. But it's not that convenient if you think about some of the following questions.

The first option requires additional work, while the second option requires you to develop on an outdated Django version. By using virtual Python environments you avoid this problem, because each project can run its own Django version in isolation.

If you consider this potential version conflict for any Python package, you'll realize why I recommend you use virtualenv. Many Python packages have specific version dependencies (e.g. Package A depends on package B version 2.3 and package C version 1.5). If you update a new package with specific cross-dependency versions, it can be very easy to break a Python installation if you're using a global Python installation. With virtualenv you can have multiple Python installations without them interfering with one another.

Now that I've explained the benefits of virtualenv, lets install the virtualenv executable with pip, as shown in listing 1-3.

Listing 1-3. Install virtualenv with pip

[user@~]$ python3 -m pip install virtualenv
Collecting virtualenv
  Downloading virtualenv-20.13.0-py2.py3-none-any.whl (2.0MB)
Installing collected packages: virtualenv
Successfully installed virtualenv-20.13.0

Listing 1-3 uses the similar python3 -m pip command -- from listing listing 1-2 -- with the install virtualenv arguments to add virtualenv to the associated python3 installation. Similar to pip which can be run as a script with Python's -m flag, virtualenv can also be run in the same manner to create virtual Python environments. Listing 1-4 illustrates how to create a virtual Python environment with virtualenv.

Listing 1-4. Create virtual Python environment with virtualenv

[user@~]$ python3 -m virtualenv coffeehouse
created virtual environment CPython3.9.10.final.0-64 in 616ms
  creator CPython3Posix(dest=/python/coffeehouse, clear=False, global=False)
  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, pkg_resources=latest, via=copy,
  app_data_dir=/home/django/.local/share/virtualenv/seed-app-data/v1.0.1.debian.1)
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

The python3 -m virtualenv command invokes the virtualenv module as a script. Following virtualenv parameters, you only need to specify an argument for the name of the virtual Python environment, which in the case of listing 1-4 is coffeehouse. There are various other virtualenv parameters to customize a virtual enviornment, which I won't describe here, but you can obtain with the command: python3 -m virtualenv --help.

By default, virtualenv creates a pristine virtual Python environment based on the initial Python installation (i.e. python3, python3.8). If you have multiple Python versions on an OS (e.g. Python 3.8, Python 3.9, Python 3.10) and you want to use a specific Python version to create a virtual enviornment, you simply need to use the desired Python executable (e.g. python3.8, python3.9) to invoke the -m virtualenv module as a script and create a virtual enviornment that uses the provided Python exectuable.

Upon execution, virtualenv creates a directory with the virtual Python environment whose contents are illustrated in listing 1-5.

Listing 1-5 - Virtual Python environment directory structure

+<virtual_environment_name>
|
|
+---+-<bin>
|   |
|   +-activate
|   +-easy_install
|   +-pip
|   +-python
|   +-wheel
|
+---+-<lib>
|
+---+-<pyvenv.cfg>
Tip Depending on the Python version used to create the virtualenv, the bin directory can contain multiple aliases or versions of the same command (e.g. In addition to python, the executables python3 & python3.10; in addition to activate, the scripts activate.csh & activate_this.py).

As illustrated in listing 1-5, a virtual Python environment has a similar directory structure to a global Python installation. The bin directory contains executables for the virtual environment, the lib directory is a copy of the global Python installation libraries and where packages for the virtual environment are installed and the pyvenv.json file contains metadata about the virtualenv, such as: the Python implementation backing the virtualenv; the Python version backing the virtualenv; and the virtualenv version, among other things.

The most important part of the virtual environment is the executables under the bin directory. If you use any of these executables, such as pip, easy_install, python or wheel they execute under the context of the virtual Python environment. For example, the pip under the bin folder installs packages for the virtual environment. Similarly, an application that runs on the python executable under the bin folder is only able to load packages installed on the virtual Python environment. This is the 'sandbox' behavior I mentioned previously.

Even though access to different virtual Python environments and executables is a powerful feature, having different pip and python executables for multiple virtual Python environments and the executables of the global Python installation itself, can become confusing due to long access paths and relative paths.

For this reason, virtualenv has a mechanism to load virtual environments so that if you execute pip, python or any other executable from anywhere on your system, the executables from a selected virtual environment are used (instead of the default global Python installation executables). This is achieved with the activate executable inside the bin directory, a process illustrated in listing 1-6.

Listing 1-6 - Activate virtual Python environment

[user@~]$ source /python/coffeehouse/bin/activate
[(coffeehouse)user@~] $ 
# NOTE: source is a Unix/Linux specific command, for other OS just execute activate

Notice in listing 1-6 how after invoking the activate executable, the command prompt adds the virtual environment name between parenthesis. This means the executables under the bin directory of the virtual Python environment coffeehouse are used over those in the global Python installation. To exit a virtual Python environment just type deactivate and you fallback to using the global Python installation executables.

As you've now learned, virtualenv works transparently allowing you to maintain different Python installations each with its own set of executables like the main python interpreter and the pip package manager. You only need to take care of switching between virtual environments so you install and run Python applications in the appropriate virtual environment.

Note In future sections I won't make any reference to virtualenv (e.g. coffeehouse) since it isn't directly related to Django. Though I recommend you use virtualenv, I'll leave it up to you if you want to keep using the global Python installation python and pip executables for everything or if you prefer to keep virtual Python environments with their own executables to make Python application management easier. So when you see Python executables referenced in the book, assume they are global or from a virtualenv, whichever you're using.

Install Django from pip

Once you have Python and pip working on your system, the actual Django installation with pip is very simple. Listing 1-7 illustrates how to install Django with pip.

Listing 1-7. Install Django with pip

[user@~]$ python3 -m pip install Django==4.0.2
Collecting Django
  Downloading Django-4.0.2-py3-none-any.whl (8.0 MB)
          |████████████████████████████████| 8.0 MB 910 kB/s 
Collecting asgiref<4,>=3.4.1
  Downloading asgiref-3.5.0-py3-none-any.whl (22 kB)
          |████████████████████████████████| 22 kB 910 kB/s  
Collecting sqlparse>=0.2.2
  Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB)
          |████████████████████████████████| 42 kB 8.0 MB/s 
Installing collected packages: asgiref, sqlparse, Django
Successfully installed Django-4.0.2 asgiref-3.5.0 sqlparse-0.4.2

The python3 -m pip install task in listing 1-7 uses the Django==4.0.2 version. With this same syntax you can install any specific Django version. If you don't specify a package version, pip downloads and installs the most recent available version for the specified package.

Sometimes a Django release can take time to become available through pip, in which case you'll receive an error. In such cases you can download the release directly from the Django main site at https://www.djangoproject.com/download/. Once you download the release file in tar.gz format, you can use pip to make the installation as illustrated in listing 1-8.

Listing 1-8. Install Django from local tar.gz file with pip

[user@~]$ wget https://www.djangoproject.com/download/4.0.2/tarball/ -O Django-4.0.2.tar.gz
[user@~]$ python3 -m pip install Django-4.0.2.tar.gz 
Processing /home/Downloads/Django-4.0.2.tar.gz
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Collecting sqlparse>=0.2.2
  Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Collecting asgiref<4,>=3.4.1
  Using cached asgiref-3.5.0-py3-none-any.whl (22 kB)
Building wheels for collected packages: Django
  Building wheel for Django (PEP 517) ... done
  Created wheel for Django: filename=Django-4.0.2-py3-none-any.whl size=8028160 sha256=206b6499c2ad5c9a35433c1e5dccfc1e58d55dec7f4ac7227b657ccaf45b401d
  Stored in directory: /home/django/.cache/pip/wheels/39/42/95/5b9135cc8b635fe64b9ce2c901de9eb642c40b6e8fa563f0e8
Successfully built Django
Installing collected packages: sqlparse, asgiref, Django
Successfully installed Django-4.0.2 asgiref-3.5.0 sqlparse-0.4.2

Notice in listing 1-8 how pip is capable of installing Python packages directly from a compressed file on the local file system.

If you want to use the most recent functionalities available in Django, then you'll need to install Django from its Git repository. The Git repository contains the latest changes made to Django. Even though the Django Git version can be unstable, it's the only way to develop with the newest Django features or get bug-fixes for problems that aren't yet available in public releases.

Note You need to install Git to execute the following tasks. Some OSes come with Git pre-installed, but you can download Git for several OSes at http://git-scm.com/

Just like the prior pip installation examples, pip is sufficiently flexible to make a Django installation from Git. There are two alternatives to use pip with Git. You can provide the remote Django Git repository, in which case pip clones the repository locally and discards it after the installation, as illustrated listing 1-9. Or you can clone the Django Git repository locally -- where you'll be able to make modifications at a later time -- and then run pip to do the installation, as illustrated in listing 1-10.

Listing 1-9. Install Django from remote Git with pip

[user@~]$ python3 -m pip install git+https://github.com/django/django.git

Collecting git+https://github.com/django/django.git
  Cloning https://github.com/django/django.git to /tmp/pip-req-build-8_fo4f66
  Running command git clone -q https://github.com/django/django.git /tmp/pip-req-build-8_fo4f66
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Collecting asgiref>=3.4.1
  Using cached asgiref-3.5.0-py3-none-any.whl (22 kB)
Collecting sqlparse>=0.2.2
  Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Building wheels for collected packages: Django
  Building wheel for Django (PEP 517) ... done
  Created wheel for Django: filename=Django-4.1.dev20220202142246-py3-none-any.whl size=8037228
  sha256=d4455552fccc672f61a56f6f0f41e7f78c3252a97be522ea7a6c98fc82bb6185
  Stored in directory: /tmp/pip-ephem-wheel-cache-k_x99n_z/wheels/41/7f/30/0dd6128695f7994687cc820d8bc0afea360f562ab5f0d21da7
Successfully built Django
Installing collected packages: asgiref, sqlparse, Django
Successfully installed Django-4.1.dev20220202142246 asgiref-3.5.0 sqlparse-0.4.2

Listing 1-10. Download Django from Git and install locally with pip

[user@~]$ git clone https://github.com/django/django.git
Cloning into 'django'...
remote: Enumerating objects: 488480, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 488480 (delta 0), reused 2 (delta 0), pack-reused 488474
Receiving objects: 100% (488480/488480), 211.13 MiB | 17.22 MiB/s, done.
Resolving deltas: 100% (357623/357623), done.
Updating files: 100% (6603/6603), done.

# Assuming Django Git download made to /home/Downloads/django/
[user@~]$ python3 -m pip install /home/Downloads/django/
Processing /home/Downloads/django
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Collecting asgiref>=3.4.1
  Using cached asgiref-3.5.0-py3-none-any.whl (22 kB)
Collecting sqlparse>=0.2.2
  Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Building wheels for collected packages: Django
  Building wheel for Django (PEP 517) ... done
  Created wheel for Django: filename=Django-4.1.dev20220202142246-py3-none-any.whl size=8037228
  sha256=99986447213cf6014db612fda727c6afc4056c2baa8f161b7b91063a02c70ef4
  Stored in directory: /tmp/pip-ephem-wheel-cache-faznv0e0/wheels/87/49/01/3f63e1128b60e72f6bfb53a5ada485f33d5b4151b839179916
Successfully built Django
Installing collected packages: asgiref, sqlparse, Django
Successfully installed Django-4.1.dev20220202142246 asgiref-3.5.0 sqlparse-0.4.2

Notice in listing 1-9 the syntax to download a remote Git repository is git+ followed by the remote Git location. In this case https://github.com/django/django.git represents the Django Git repository. In listing 1-10 the Django Git repository is cloned locally first with git clone and Django's Git url, followed by running pip on the local Git repository directory.

Install Django from OS package manager

It's also possible to install Django with the aid of an OS package manager. Unlike pip that can potentially run on multiple Python versions on the same OS with the help of virtualenv, relying on an OS package manager means a Django installation runs on the global OS Python installation.

One of the positives of this installation approach is there's little to no confusion about what Django version is running, since there's only one global Python installation accessible from any part of the OS. Another positive aspect of this approach is the OS package manager is in charge of managing updates -- security or otherwise -- which makes this installation have better monitoring.

Among the negatives of this installation approach is that it's managed by OS maintainers, which means it tends to be even slower than pip to publish new Django releases. Another drawback of using OS package managers to install Django is they're severely fragmented -- unlike pip which behaves identically across OSes -- this means every OS package manager uses different conventions (e.g. installation directories, configuration files, package name, etc) making it more cumbersome to know where to change things.

Listing 1-11 illustrates how to install Django with the Linux apt package manager.

Listing 1-11. Install Django with Linux apt package manager

[user@~]$ sudo apt install python3-django
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  python3-sqlparse
Suggested packages:
  bpython3 geoip-database-contrib ipython3 libgdal20 python-django-doc python3-flup python3-memcache python3-mysqldb python3-psycopg2 python3-selenium
  python3-sqlite python-sqlparse-doc
The following NEW packages will be installed:
  python3-django python3-sqlparse
0 upgraded, 2 newly installed, 0 to remove and 8 not upgraded.
Need to get 2,694 kB of archives.
After this operation, 23.5 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://archive.ubuntu.com/ubuntu focal/main amd64 python3-sqlparse all 0.2.4-3 [28.1 kB]
Get:2 http://archive.ubuntu.com/ubuntu focal-security/main amd64 python3-django all 2:2.2.12-1ubuntu0.10 [2,666 kB]
Fetched 2,694 kB in 2s (1,472 kB/s)       
Selecting previously unselected package python3-sqlparse.
(Reading database ... 305219 files and directories currently installed.)
Preparing to unpack .../python3-sqlparse_0.2.4-3_all.deb ...
Unpacking python3-sqlparse (0.2.4-3) ...
Selecting previously unselected package python3-django.
Preparing to unpack .../python3-django_2%3a2.2.12-1ubuntu0.10_all.deb ...
Unpacking python3-django (2:2.2.12-1ubuntu0.10) ...
Setting up python3-sqlparse (0.2.4-3) ...
Setting up python3-django (2:2.2.12-1ubuntu0.10) ...
Processing triggers for man-db (2.9.1-1) ...

Notice how the Django apt installation in listing 1-7 uses the more verbose package name python3-django vs. pip's naming convention Django. In addition, notice how the Django version installed with apt corresponds to Django 2.2.12, which is a relatively old Django version.

Install Django from Python's PYTHONPATH

The previous approaches to install Django all make use of a separate workflow to make it easier to manage the files that compose Django. However, with Django being composed of Python modules, it's perfectly valid to forgo this separate workflow and simply tell Python where it can locate Django through Python's PYTHONPATH environment variable.

When you run Python's executable (e.g. python3, python3.9) it uses the PYTHONPATH environment variable to determine on which directories to look for Python modules. This is similar to how after installing something with pip, it becomes automatically available on its associated Python executable. In this manner, it's possible to use the PYTHONPATH environment variable and have Python access Django on a file system directory of your choice.

One of the positives of this installation is you have direct control over where Django source files are stored in a file system directory, making it easy to tweak or update core parts of the framework vs. the earlier installation approaches where you need to search around internal file system directories to find Django's core files. Another positive aspect is that if Django is managed through a version control system like Git, it's very easy to perform a one step update to run Django with the latest or a specific version.

Among the negatives of this installation approach is it can be easy to forget and configure PYTHONPATH with the directory that contains Django vs. pip which makes things available automatically.

Listing 1-12 illustrates how to install Django with the PYTHONPATH environment variable and Django versions obtained from a tar.gz file -- like it's done in listing 1-8.

Listing 1-12. Install Django with tar.gz file and PYTHONPATH environment variable

# Get tar.gz files for different versions
[user@~]$ wget https://www.djangoproject.com/download/4.0.2/tarball/ -O Django-4.0.2.tar.gz
[user@~]$ wget https://www.djangoproject.com/download/3.2.12/tarball/ -O Django-3.2.12.tar.gz
# Unpack tar.gz files
[user@~]$ tar -xzvf Django-4.0.2.tar.gz
[user@~]$ tar -xzvf Django-3.2.12.tar.gz

[user@~]$ python3
Python 3.9.10 (main, Jan 15 2022, 18:17:56) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
import django
Traceback (most recent call last):
  File "", line 1, in 
ModuleNotFoundError: No module named 'django'

[user@~]$ export PYTHONPATH=/home/django/Downloads/Django-4.0.2/:$PYTHONPATH

[user@~]$ python3
Python 3.9.10 (main, Jan 15 2022, 18:17:56) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.__version__
'4.0.2'

[user@~]$ export PYTHONPATH=/home/django/Downloads/Django-3.2.12/:$PYTHONPATH

[user@~]$ python3
Python 3.9.10 (main, Jan 15 2022, 18:17:56) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.__version__
'3.2.12'

Listing 1-12 starts by downloading and unpacking two different Django versions in tar.gz format. The two Django versions are unpacked into folders with the Django version: Django-4.0.2 and Django-3.2.12. Next, you can see the Python interactive session attempts to access Django with the import django statement which returns the error ModuleNotFoundError: No module named 'django', confirming the Python installation doesn't have Django.

Next, listing 1-12 shows the first modification to the PYTHONPATH environment variable: export PYTHONPATH=/home/django/Downloads/Django-4.0.2/:$PYTHONPATH. The export PYTHONPATH statement is how environment variables are typically set inline on Linux systems, with export followed the environment variable name. The value /home/django/Downloads/Django-4.0.2/:$PYTHONPATH tells Python it should attempt to first lookup modules in the /home/django/Downloads/Django-4.0.2/ directory (i.e. where the Django tar.gz was unpacked), followed by other directories specified and separated by :. In this case, the $PYTHONPATH syntax is a way to substitute the previous value of PYTHONPATH and append it to the new value, in other words, if the initial PYTHONPATH value is /home/python/utils/:/usr/local/python/libs/ the statement export PYTHONPATH=/home/django/Downloads/Django-4.0.2/:$PYTHONPATH gets substituted to export PYTHONPATH=/home/django/Downloads/Django-4.0.2/:/home/python/utils/:/usr/local/python/libs/ where Python first attempts to lookup modules in /home/django/Downloads/Django-4.0.2/, followed by /home/python/utils/ and then /usr/local/python/libs/.

With Python's PYTHONPATH enviornment variable updated, listing 1-12 shows another Python interactive session that attempts to access Django with the import django statement, in this case, it succeeds. After this step, a call is made to django.__version__ to print the installed Django version 4.0.2. As you can see, by modifiying the PYTHONPATH enviornment variable, it's entirely possible to give Python access to Django without the need to use pip or an OS package manager.

The next step in listing 1-12 consists of modifying the PYTHONPATH environment variable yet again to point toward the Django version in the directory /home/django/Downloads/Django-3.2.12/. Once this is done, another Python interactive session is started confirming the Django version is now 3.2.12. The reason Python now sees the Django 3.2.12 version and not the earlier 4.0.2 version, is because Python attempts to resolve names in the order in which they're declared in PYTHONPATH. Because Python is able to find the django module in the first PYTHONPATH directory (i.e. /home/django/Downloads/Django-3.2.12/), it loads this first and ignores any other declared directory that might contain the same module.

Warning The PYTHONPATH environment variable effectively modifies the precedence in which Python loads modules, including Django. This means that if you install Django through pip or an OS package manager and then update PYTHONPATH with a directory that also contains Django, Python uses the first Django version instance it finds through PYTHONPATH ignoring all others (i.e. Django versions installed through pip or an OS package manager).

Listing 1-13 illustrates how to install Django with the PYTHONPATH environment variable and Django versions cloned from Git -- like it's done as described in listing 1-10.

Listing 1-13. Install Django with Git and PYTHONPATH environment variable

# Clone Django with Git
[user@~]$ git clone https://github.com/django/django.git
Cloning into 'django'...
remote: Enumerating objects: 488480, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 488480 (delta 0), reused 2 (delta 0), pack-reused 488474
Receiving objects: 100% (488480/488480), 211.13 MiB | 17.22 MiB/s, done.
Resolving deltas: 100% (357623/357623), done.
Updating files: 100% (6603/6603), done.

[user@~]$ export PYTHONPATH=/home/django/Downloads/git/django/:$PYTHONPATH

[user@~]$ python3
Python 3.9.10 (main, Jan 15 2022, 18:17:56) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.__version__
'4.1.dev20220203190912'

# Update Git repo to specific Django version
[user@~]$ cd /home/django/Downloads/git/django/
[user@~]$ git checkout 3.2.12
[user@~]$ cd 

[user@~]$ python3
Python 3.9.10 (main, Jan 15 2022, 18:17:56) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.__version__
'3.2.12'

# Update Git repo to go back to latest Django version
[user@~]$ cd /home/django/Downloads/git/django/
[user@~]$ git checkout origin
[user@~]$ cd 

[user@~]$ python3
Python 3.9.10 (main, Jan 15 2022, 18:17:56) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.__version__
'4.1.dev20220203190912'

Listing 1-13 starts by cloning Django's Git repository, allowing us access to any Django version. Next, you can see the the PYTHONPATH environment variable is set to export PYTHONPATH=/home/django/Downloads/git/django/:$PYTHONPATH, where /home/django/Downloads/git/django/ represents the location of the Django Git repository, specifically, /home/django/Downloads/git/ being the directory where the git clone https://github.com/django/django.git action was taken and the last sub-directory django/ being created by Git.

With Python's PYTHONPATH environment variable updated, listing 1-13 shows a Python interactive session that confirms the installation of Django version 4.1.dev20220203190912. As you can see, by modifying the PYTHONPATH environment variable, it's entirely possible to give Python access to Django without the need to use pip or an OS package manager.

The next step in listing 1-13 consists of using the git checkout command to change Django's Git repository to a specific version. By running git checkout 3.2.12 while placed in the Django Git repository, an update is made to reflect all the files in the repository be from the Django 3.2.12 version. Once again, another Python interactive session is started confirming the Django version is now 3.2.12. And as simple as running this git checkout, Python is able to switch between different Django versions vs. the workflow overhead of installing/overwriting/re-installing Django packages via pip or an OS package manager.

The final step in listing 1-13 consists of doing another git checkout operation on Django's Git repository, but this time with git checkout origin to return all files in the repository to the latest Django version. Once this is done, another Python interactive session is started confirming the Django version is back to 4.1.dev20220203190912.

Warning The PYTHONPATH enviornment variable effectively modifies the precedence in which Python loads modules, including Django. This means that if you install Django through pip or an OS package manager and then update PYTHONPATH with a directory that also contains Django, Python uses the first Django version instance it finds through PYTHONPATH ignoring all others (i.e. Django versions installed through pip or an OS package manager).
  1. https://www.djangoproject.com/download/    

  2. https://github.com/django/django/