How to Use a Virtual Environment to run you Django app

The best way to use Python especially Django is by creating what is called a “Virtual Environment”. This is a separate instance of Python that you can install all the tools that you need to run your Django app without having to messing up your current Python instance.

It will also help to freeze the packages you install which is great for deploying to different environments and such. But, the steps are pretty much the same everything you create a new Virtual Environment. These steps are assuming you use a Unix based operating system. If you are using Windows, these steps will be a little different.

Step 1: Install ‘virtualenv’

First things first. You need to install virtualenv. You can do this with the ‘pip’ command.

$ pip install virtualenv

Step 2: Create your virtual environment

The next step to creating a virtual environment is to actually create it. This step will install an instance of Python and also install Pip for you so you can install the packages that you want.

$ virtualenv venv

You can call the virtual environment anything you like. I like to call it ‘venv’

Step 3: Activate the virtual environment

This step will change your Python path so that you will use the virtual environment version of Python and Pip. You’ll notice that when you enter this command, you might see ‘(venv)’ next to your commandline. That’s how you know that you’re running the virtual environment

$ source venv/bin/activate

Step 4: Install your packages

You can then install your packages at this point. You’ll be happy to know that you’re packages will be installed inside of your virtual environment. So, when you try to ‘import django’, the Python interpreter will be able to find it.

Step 5: Deactivate your virtual environment

When you are done working on your Django app, and you want to exit from your virtual environment, simply call:

$ deactivate

You’ll be back to your default Python path.

Struggle with the Django Documentation?

If this post helped you, sign up for my newsletter and you'll get a new post each week that will help you master Django ABSOLUTELY FREE!

Powered by ConvertKit