Install Python Virtualenv with Django

Virtualenv allow you to package all python modules within one folder, keeping your code seperate from local environment. It is ideal if you are running multiple version of Python or other frameworks (like Django) on your machine.

This post is briefly about how to get up and running in a few minutes using virtualenv and Django.

Install virtualenv

Installing virtualenv is easy on a Linux or Mac system, but the instructions that follow are Linux (Ubuntu, actually) specific. First you'll need setuptools:

$ sudo apt-get install python-setuptools

Then we can easy_install virtualenv:

$ sudo easy_install virtualenv

We need to use sudo here because it has to install to a global location. Don't worry, this is the last time we'll need to do something as root.

Create your virtualenv

cd to wherever it is you keep your projects (for me, in ~/src), and run:

$ virtualenv --no-site-packages ENV

In this instance I've chosen ENV as the name for my virtual environment. The —no-site-packages command tells virtualenv not to symlink the global site packages into my local environment, just take the Python standard library. This is important, because it helps us avoid the dependency difficulties mentioned above.

Activate environment

$ cd ENV
$ source bin/activate

You will now be running under your virtual environment, for example on my machine:

$ (ENV)Guillaume-Piots-MacBook-Pro:ENV

Now you can any python command as you use to.

Installing Django

Now, the trick with virtualenv is that it creates its own Python and easy_install binaries, which means you can install/run things specifically in your environment. Let's install Django:

$ easy_install django

And it's done. easy. You might also want to install the MySQL bindings and IPython for ease of use:

$ easy_install MySQL-python

Tip: you may need to setup your mysql path first > PATH=/usr/local/mysql/bin:$PATH

To start a new Django project, you'll note that a file will have been installed for you in the environment:

$ startproject myapp

Obviously you can skip this step if you have an existing Django project.

Running Django

Now the last step, which is probably obvious by now, is to run Django's runserver with the virtual Python binary:

$ cd myapp
$ python runserver

And you're away!


Just make sure whenever you need to add another package that you install it in the virtualenv, and not in the global packages directory. If you want to deploy using virtualenv, here are some instructions for using mod_wsgi with virtualenvs.

< / >