Virtual Environments
You start the cookbook on the newest Django. Next month you pick up an older site that must stay on an earlier version. If both live in the same Python installation, installing one quietly replaces the other, and a project that worked yesterday breaks today. The fix takes one command, and you run it before anything else.
The rule
One project, one environment: packages never share a home.
A virtual environment is a folder that holds its own copy of Python's package directory. While it is active, python and pip point into that folder, so whatever you install lands there and nowhere else.
Python ships the tool for this, venv. From inside the project folder:
mkdir cookbook && cd cookbook
python3 -m venv .venv # create it (use "python" on Windows)
source .venv/bin/activate # activate on macOS / Linux
# .venv\Scripts\activate # activate on WindowsYour prompt usually gains a (.venv) prefix to show which environment is live. Check it any time:
python -c "import sys; print(sys.prefix)" # prints a path ending in .venvTo leave, run deactivate. The folder stays; activate it again next session.
Three habits keep this painless:
- Name it
.venvand keep it inside the project folder, so it is obvious which environment belongs to which project. - Never commit it. Add
.venv/to.gitignore; it is rebuilt from a list of requirements instead. - If an environment gets into a strange state, delete the folder and create a fresh one. It holds nothing you wrote.
Other tools, such as virtualenv, pipenv, poetry and uv, manage environments too. They differ in comfort, not in the idea.
The shortcut
Before any pip install, glance at the prompt: no (.venv), no install. Activation is the switch that decides where packages go.
Make the folder
mkdir cookbook && cd cookbook. Everything for this project lives here.
The classic mistake is opening a new terminal, forgetting to activate, and installing into the system Python. The project then says "No module named django" even though you "just installed it".
Drills
Answer fast — trust the rule.
Which command creates a virtual environment in a folder named .venv?
Should the .venv folder be committed to Git?
You open a new terminal and run pip install Django without activating. Where does Django go?
How do you leave an active virtual environment?
Remember
- One project, one environment: packages never share a home.
- No
(.venv)in the prompt, no install. - Trap: a new terminal is not activated, and
.venvnever goes into Git.
