Last Updated: February 25, 2016
· lemuelf

Automatically enable django's bash completion on virtualenv activate (using virtualenvwrapper)

If you are using virtualenvwrapper to activate your python virtual environments, you can make virtualenvwrapper automatically source the django_bash_completion script when you activate your django environment, which will give your bash environment tab-completion for and commands and command options.

Run the following in your shell to hook the script in your virtualenv's postactivate event (replace my_django_env with the name of your django virtualenv):

$ workon my_django_env  # (1)
$ echo 'source "${VIRTUAL_ENV}/src/django/extras/django_bash_completion"' >> ${VIRTUAL_ENV}/bin/postactivate  # (2)
$ workon my_django_env  # (3)

What the above commands do:
(1) activates your django project environment, so the shell environment variables of the virtualenv gets set, which we will use in the next command
(2) hooks the sourcing of djangobashcompletion in your current virtualenv's post-activate event
(3) re-activates your django project virtualenv so the completion script gets sourced in the current shell

After issuing the above commands in your shell, you now have tab-completion for and commands (and command options) in your current shell, and in new shells after you "workon" with your django project virtualenv.

Note that the above steps require that you have installed an "editable" checkout of django's source since the extras directory, which contains the djangobashcompletion script, isn't in the django python package (it's not a python module). If you are using the django python package in your requirements with a "frozen" version, say,


you can change it into an editable git checkout with the following entry, with the same version specified as a git tag:


After you have changed your django installation from the python package and into the editable git checkout, you should now have the extras directory in your virtualenv and can now source the django_bash_completion script detailed in the upper half of this protip.