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.
git clone path-to-github.git new_directory_name
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:
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.
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"
Leaving the Virtualenv
To deactivate the virtual environment, run the following after you have activated the environment.
Do you have any tips for improving my workflow? Was this helpful to you? If so, let me know.