Using Virtual Environments in Django
At first I was a little hesitant to virtual environments in Django. Not because I didn't think it was a good idea, but because it seemed like a lot of extra work. After finally spending some time learning more about it, I can tell you that overall it is pretty easy and I would highly recommend it for all Django development.
Using Virtual environments not only makes rebuilding your environments easier, it also makes deploying to a service such as Heroku or Google App Engine possible. Here is the general workflow I use when dealing with virtual environments.
Create environment
git clone path-to-github.git new_directory_name
cd new_directory_name
virtualenv venv
All my Django projects have a requirements.txt file saved in the git repository. I download those requirements by running
pip install -E venv -r ./requirements.txt
Using the Virtual Environment
Before starting my development or debugging, I simple open up the command line, navigate to the new folder I created and run:
source venv/bin/activate
Then I begin my development by running the Django development server:
python project_name/manage.py runserver
As a reference, I structure my git repo in this way
- Git Repository Root (in this example it would be new_directory_name)
- - Procfile (used for deployment on Heroku)
- - requirements.txt (contains my projects requirements)
- - venv (folder containing virtual environment information)
- - .gitignore (Git Ignore file, more information below)
- - project (the folder containing my Django code, in this example it would be project_name)
My gitignore file contains the following to prevent virtual environment information or .pyc files from making it into the repo.
venv
*.pyc
You can install packages in the virtual environment by running:
pip install packagename
You can then save these requirements by running
pip freeze > requirements.txt
If I make code changes or requirements changes that I need to push up I run the following (standard git commands):
git add .
git commit -m "My Commit message"
git push
Leaving the Virtualenv
To deactivate the virtual environment, run the following after you have activated the environment.
deactivate
Do you have any tips for improving my workflow? Was this helpful to you? If so, let me know.



Discussions
Thanks!
I had no idea about the pip freeze command. Until now I'd been keeping a manual list of requirements. This saves me a load of time, and is more accurate. Thanks!
Really helpful material for
Really helpful material for newcomer to django and virtual-env
Post new comment