Image for post
Image for post

Creating a Virtual Environment for Django

The importance of creating a virtual environment before starting a Django project and a walkthrough of how to do it yourself.


At one of my very first internships, I was tasked with the creation and development of a Django project. I had no idea what a virtual environment was so when it came time to deploy, I ran into some trouble. The problem was that it was very difficult to distinguish between packages that the project depended on and packages already installed on my computer. My mentor told me to treat this as a lesson learned that creating a virtual environment should be the first thing done when creating a Django project.


In this walkthrough we will demonstrate:

  1. Creating a virtual environment

What is a virtual environment exactly?

A virtual environment isolates the packages installed on our computer from those used by our Django project. As you continue to develop a project chances are that you will continue to install packages to add more functionality. If you’re not using a virtual environment, the more difficult it is to track which of them your project is using and which ones were previously installed on your computer.

Creating a Virtual Environment

The virtual environment is simply a directory that will live inside the root directory of our project called venv which we'll create in this step. First, we'll cd into to the directory that you want to create the project in and create a directory called myproject.

$ cd Documents
$ mkdir myproject

Next, we’ll create a virtual environment inside our project directory.

$ cd myproject
$ python3 -m venv venv

Activating the Virtual Environment

Question: When installing packages how does terminal know to install it on our virtual environment?

Answer: By activating a virtual environment on the terminal window used to install packages.

In this step we’ll create a requirements.txt file to specify which packages we want installed on our virtual environment.

$ source venv/bin/activate

After running this command, we’ll notice (venv) being displayed to the left of our terminal like this.

(venv) ~$

This means that the virtual environment is activated. And anything installed on this terminal window will be installed on our virtual environment, not our computer environment.

Installing Django onto the Virtual Environment

To let our virtual environment know which version of Django we want to install we will create a file called requirements.txt...

(venv) ~$ touch requirements.txt

…with the package name and version number within it.


Now we’ll install Django to our virtual environment.

(venv) ~$ pip install -r requirements.txt

Written by

Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store