If you find yourself in a situation where you have to work with multiple Django projects on the same system, where each one requires a specific version of Django(and some other libraries), or even specific version of Python(2.5/2.6..), the combination of virtualenv and pip will make your life easier.
virtualenv is tool to create isolated Python environments.
pip is a Python package installer, much like easy_install. It’s complementary with virtualenv; you’ll use pip to install, upgrade, or uninstall packages in isolated virtualenvs.
In this post, I’ll show a simple workflow that will give you the basics on how to use these tools to manage multiple Django projects.
Installation
First, get these tools installed on your machine. If you have easy_install set up, you can install pip by just issuing the following command
sudo easy_intsall pip
Now install virtualenv, using pip itself
sudo pip install virtualenv
Creating virtualenvs
Now that you have them installed, let’s try creating some virtualenvs. It’s good to have a specific location on your machine where you would have all the virtualenvs. I personally like to have them under ~/.virtualenvs directory.
Create the directory
mkdir -p ~/.virtualenvs
Navigate into it
cd ~/.virtualenvs
Create a virtualenv
virtualenv -p python2.5 --no-site-packages projectA
The ‘-p’ option specifies which version of the Python interpreter you want to use for the virtualenv(In case you have multiple in your system). If not specified, the default interpreter will be used.
The ‘–no-site-packages’ option means do NOT inherit any packages from /usr/lib/python2.5/site-packages (or wherever your global site-packages directory is). Use this if you don’t want depend on the global packages and want more isolation.
Finally ‘projectA’ is the name of the virtualenv, named after the project itself(not a rule, just a good convention).
You’ll see the directory projectA created once the command prompt returns. This is the virtualenv, feel free to explore it.
Activating/Deactivating the virtualenv
Once pip have finished downloading and installing the packages, hopefully without any glitches, activate the virtualenv
source ~/virtualenvs/projectA/bin/activate
You should see “(projectA)” in your command prompt.
To deactivate it type ‘deactivate’ in your prompt and hit enter. The “(projectA)” should disappear.
So now you have an isolated and functional environment for your Django project. You should go ahead and create a new virtualenv with more recent versions of Python/Django as your homework.
I hope you’ve got the basics properly. Check out the online docs to learn more advanced usages of these tools.
In the next post, I’ll talk about virtualenvwrapper, a tool that makes managing multiple virtualenvs a little easier.