Running Django manage.py commands from anywhere

One of the most annoying aspects of developing in Django for me is running manage.py commands: you need to be in the same directory with manage.py file in order to run a command. This is not convenient. I thought it would be cool to be able to run manage.py from anywhere in the project as much as you can run git command from anywhere within a git project.

The solution is simple: create a bash script that accepts manage.py arguments, takes your current directory and searches for manage.py file in that directory recursivelly and then if file not found there, find goes up a directory and up and up until it finds nearest manage.py or hits the root ('/'). When it finds manage.py it executes it with arguments passed to the bash script. Simple idea, let's implement:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
  1. #!/bin/bash
  2. managepy_path=0
  3. while [[ "`pwd`" != '/' ]]; do
  4. managepy_path=$(find $(pwd) -type f -name "manage.py" -print | head -n 1)
  5. if [[ -n $managepy_path ]]; then
  6. echo "Running 'python $managepy_path $@' command:"
  7. python $managepy_path $@
  8. break
  9. else
  10. cd ..
  11. fi
  12. done
  13. if [[ managepy_path == 0 ]]; then
  14. echo 'Cant find manage.py'
  15. fi

Save it to your local bin: /usr/local/bin as manage.py (yes, this is not python file, but it has .py extension to make it sound as vanilla Django manage.py file, you can name it anything you want actually).

And then run it from somewhere deep in your Django project:

1
  1. manage.py --help

And you'll get the output of the nearest manage.py command executed within your currently activated virtualenv or default python environment.

Git repo

I added the script to its very own git repo at https://github.com/timonweb/Django-manage.py-anywhere">https://github.com/timonweb/Django-manage.py-anywhere and you can now use pip to install the package:

1
  1. pip install django_managepy_anywhere

Enjoy and let me know how it works for you :)