← Back to Chapters

Creating a Virtual Environment

? Creating a Virtual Environment

? Quick Overview

A virtual environment allows you to isolate your project's dependencies and prevent them from conflicting with other projects. This is a good practice to ensure that your development environment is clean and easily manageable. Here's how to create and use a virtual environment for your Django projects.

? Key Concepts

  • Each project has its own Python packages
  • No dependency conflicts between projects
  • Clean and reproducible development setup

? Step 1: Install virtualenv

? View Code Example
# Install virtualenv if it is not already installed
pip3 install virtualenv

This will install virtualenv, a tool to create isolated Python environments.

? Step 2: Create a Virtual Environment

? View Code Example
# Create a virtual environment named myenv
python3 -m venv myenv

This command creates a directory named myenv that contains the isolated Python environment.

? Step 3: Activate the Virtual Environment

? View Code Example
# Activate virtual environment on Linux or macOS
source myenv/bin/activate
# Activate virtual environment on Windows
myenv\Scripts\activate

Once activated, your terminal shows the environment name.

? Step 4: Install Django

? View Code Example
# Install Django inside the active virtual environment
pip install django

? Step 5: Deactivate the Environment

? View Code Example
# Exit from the virtual environment
deactivate

? Explanation

  • Installing virtualenv: Provides tools to create isolated environments.
  • Creating environment: Generates a dedicated Python setup.
  • Activating: Ensures packages install only inside the environment.
  • Installing Django: Keeps project dependencies clean.
  • Deactivating: Returns to global Python safely.

? Interactive Example

Click the buttons to simulate terminal behavior:

C:\Users\Dev> No Environment Active

? Use Cases

  • Django and Flask projects
  • Multiple Python versions
  • Team-based development

✅ Tips & Best Practices

  • Always create a virtual environment per project
  • Use requirements.txt for dependency tracking
  • Activate the environment before coding

? Try It Yourself

  • Create a virtual environment
  • Install Django inside it
  • Run pip freeze to inspect packages