Wednesday, July 3, 2013

Never Have to Type "python" with Django Again

I got very quickly got tired making sure I was in the right directory and typing python I found django-shortcuts but didn't like the fact that it only mapped a handful of the commands and I wanted access to everything could do.

I then briefly considered creating a bash function that would determine's location on every invocation but figured that was silly and decided I might as leverage virtualenv's virtual environment and as Ron Popiel says, "You set it and forget it!"

It only took a minute of poking to find the postactivate hook file within my ~/.virtualenvs directory. Below is the fruit of my labor.

# ~/.virtualenvs/postactive
# This hook is run after every virtualenv is activated.
    MANAGE_PY=$(find "$SRC_DIR/$VIRTUAL_ENV_NAME" -name "" -type f)
    if [ -e "$MANAGE_PY" ]
        alias django="python $MANAGE_PY"
        unalias django
    unalias django

The end result is that I have a new django alias that will work anywhere and act as though I typed python

jbisbee@beni:~$ workon django-tutorial
(django-tutorial)jbisbee@beni:~$ alias | grep django
alias django='python /Users/jbisbee/src/django-tutorial/mysite/'

Disclaimer: I'm making a big assumption here that the virtualenv name you're using is identical to the name of the project you're working on. It's a pretty big assumption so I apologize if it does't work right out of the box for you.

1 comment:

  1. Happy to see I'm not the only one that hates typing My `django` alias walks up the directory tree based on how fabric finds fabfile. It's not pretty, but it works so I've never cleaned it up: