← Back to Django Course | Chapter 1: Django Fundamentals & Setup | Lesson 4 of 9

Python Virtual Environments

A virtual environment is like a separate toy box for each project, so the toys from one project don't mix with another.

Why Virtual Environments Matter

Different projects can need different versions of the same package; a virtual environment keeps each project's packages separate so they never conflict with each other.

Example: Why Virtual Environments Matter

Run after activating a venv, this installs Django 4.2 only inside that project's venv — a different project's venv can have Django 5.0 installed at the same time with no conflict.

bash
pip install django==4.2

⚠️ Run this command in your terminal.

Creating a Virtual Environment

Running "python -m venv venv" creates a new folder named "venv" containing an isolated copy of Python and pip just for this project.

Example: Creating a Virtual Environment

Creates a new virtual environment folder named venv in the current directory.

bash
python -m venv venv

⚠️ Run this command in your terminal.

Activating the Virtual Environment

On Linux or macOS you activate the environment with "source venv/bin/activate"; once active, your terminal prompt changes and any pip install goes into that environment only.

Note: Deactivate anytime with the "deactivate" command.

Example: Activating the Virtual Environment

Activates the virtual environment so installed packages stay isolated to this project.

bash
source venv/bin/activate

⚠️ Run this command in your terminal.

Confirming the Active Environment

Running "which python" after activation shows the Python interpreter now points inside the venv folder, confirming the isolated environment is active.

Warning: On Windows the equivalent command is "where python".

Example: Confirming the Active Environment

Prints the path of the active Python interpreter to confirm the virtual environment is in use.

bash
which python

⚠️ Run this command in your terminal.

Common Mistakes
  1. Installing project packages globally, causing conflicts between projects that need different versions.
  2. Forgetting to activate the virtual environment before installing packages.
  3. Committing the virtual environment folder itself into version control instead of ignoring it.
Chapter Summary
  • A virtual environment isolates a project's Python packages from the rest of the system.
  • The "venv" module (built into Python) creates virtual environments.
  • You must activate a virtual environment before installing packages into it.
  • Each project can have its own virtual environment with different package versions.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.