How to Use a Virtual Environment to run you Django app

Posted by Chris Bartos on March 1, 2016

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 2.5: Customize your Python version

If you want to create a virtual environment with a different version of Python, use the following command:

$ virtualenv -p python3.6 venv

Note, that python3.6 has to be a Python executable in your path. If you don’t have python3.6 in your path, you need to download it and put it in your path. NOTE: How you do this depends on your operating system. Email me if you have questions.

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.

Need help with Django REST Framework? Django REST Framework documentation a little confusing?

Join me for my FREE Django REST Framework email course:

Django REST Framework Email Course

You'll get 1 lesson everyday for 7 days.
You'll learn:

  • Serializers
  • Request Methods
  • Endpoints
  • Basic Authentication
  • JQuery Integration
  • AngularJS Integration
Powered by ConvertKit

Similar Posts

What is SECRET_KEY in Django?
What is a Mixin