Wednesday, July 3, 2013

Never Have to Type "python manage.py" with Django Again

I got very quickly got tired making sure I was in the right directory and typing python manage.py. 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 manage.py could do.

I then briefly considered creating a bash function that would determine manage.py'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.

#!/bin/bash
# ~/.virtualenvs/postactive
# This hook is run after every virtualenv is activated.
VIRTUAL_ENV_NAME=$(basename $VIRTUAL_ENV)
SRC_DIR="$HOME/src"
if [ -d "$SRC_DIR/$VIRTUAL_ENV_NAME" ]
then
    MANAGE_PY=$(find "$SRC_DIR/$VIRTUAL_ENV_NAME" -name "manage.py" -type f)
    if [ -e "$MANAGE_PY" ]
    then
        alias django="python $MANAGE_PY"
    else
        unalias django
    fi
else
    unalias django
fi

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

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

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 manage.py. 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: https://github.com/crccheck/dotfiles/blob/master/bin/django

    ReplyDelete