In this tutorial, we'll explore how to set up virtual environments for Django development. The goal is to provide you with the requisite knowledge needed to create isolated spaces, known as virtual environments, where you can install Python packages without interference.
By the end of this tutorial, you will understand:
- What a virtual environment is and why it's important
- How to create a virtual environment
- How to activate and deactivate a virtual environment
- How to install Django in the virtual environment
Prerequisites: This tutorial assumes you have Python installed on your system. If not, please install it before proceeding.
A virtual environment is an isolated workspace where you can install Python packages without them affecting your system or other projects. It is especially useful when working on multiple projects that require different versions of the same package.
To create a virtual environment, use the venv
module that comes with Python. Open your terminal and navigate to the directory where you want to create your environment. Then, run the following command:
python3 -m venv myenv
This command creates a virtual environment named myenv
. You can replace myenv
with any name you prefer.
To start using your virtual environment, you need to activate it. The command differs based on your operating system.
For UNIX or MacOS, use:
source myenv/bin/activate
For Windows, use:
myenv\Scripts\activate
With the virtual environment activated, you can now install Django using pip:
pip install Django
Example 1: Creating a virtual environment
python3 -m venv myenv
This command creates a new virtual environment named myenv
.
Example 2: Activating the virtual environment on UNIX or MacOS
source myenv/bin/activate
After running this command, you'll see (myenv)
before your prompt, indicating that the environment is active.
Example 3: Installing Django in the virtual environment
pip install Django
This command installs Django in the active virtual environment. You can verify the installation by running django-admin --version
.
In this tutorial, we've covered the basics of setting up virtual environments for Django development. We've learned how to create, activate, and install packages in virtual environments.
For further learning, consider exploring how to manage different package versions in separate environments, or how to use virtual environments with your favorite IDE.
Solution
python3 -m venv test_env
source test_env/bin/activate
. For Windows: test_env\Scripts\activate
pip install Django==3.0
then django-admin --version
to verify the installed version.