[Django]-Django and 'virtualenv' – proper project structure

18👍

It doesn’t really matter where you store your virtual environment. Find a project structure that works for you.

I wouldn’t put the virtual env inside the project, because you shouldn’t check it into version control (although you could use an ignore). Normally, you just need to check in your requirements file, so that you can recreate the environment.

I wouldn’t put the project inside the virtual env, because virtual envs are disposable. You might want to destroy the virtual env without destroying the project. Also, you might want to run the same project under different virtual envs e.g. test your code on Django 1.8 and 1.9 before upgrading.

You might find virtualenvwrapper useful. It has some tools that make it easy to create and switch between virtual environments. It stores all of your virtual environments in one place, so you don’t have to worry about where to put them.

Is this correct or can I do it without activating virtual environment first?

You should activate the virtual environment and install django before you create / work on your project.

26👍

Common solution is to keep virtual environments and projects in separate folders, e.g. have /users/myUser/.venvs for virtual environments and /users/myUser/documents/projects/ for projects. In other aspects you got it pretty much right yourself. So:

  1. You need to install global Python and virtualenv.
  2. Create directoriy for virtual environments, e.g. run mkdir /users/myUser/.venvs.
  3. Create the virtual environment for your project, virtualenv /users/myUser/.venvs/project1_venv.
  4. Activate the environment for your current shell session /users/myUser/.venvs/project1_venv/bin/activate.
  5. Install django and anything else in this environment pip install django, or better use requirements.txt file to keep track of all project dependencies.
  6. Deactivate the environment, run deactivate.

Now when you’ll want to run your project using created virtual environment, in your console window run /users/myUser/.venvs/project1_venv/bin/activate and then python /users/myUser/documents/projects/project1/manage.py runserver. You can activate the venv from any directory, it’s activated for current shell window and any python ... run in that window after activation will use this virtual environment. The activation script modifies environment variables in a way, so that the interpreter and libraries from venv are used instead of global ones. (Though there are options to use global ones too.)

👤Nikita

Leave a comment