djangodeis

How do I run Django migrations automatically on Deis when using a buildpack deployments?


The post-compile hook on Deis seems to function differently than on Heroku.

On Heroku I could simply add a bin/post-compile file containing:

#!/usr/bin/env bash

python manage.py migrate --noinput

On Deis this gives me a traceback

Traceback (most recent call last):        
    File "manage.py", line 8, in <module>        
        from django.core.management import execute_from_command_line        
No module named django.core.management      

Is anyone running Django on Deis using buildpacks and have a working example of this?


Solution

  • I have eventually found two solutions.

    The simple answer is to just provide a full path to python. I've tested this by adding a bin/post-compile file to deis/example-python-django

    #!/usr/bin/env bash
    
    /app/.heroku/python/bin/python manage.py migrate --noinput
    

    This solution however doesn't work if you need access to any of your config variables, which is most likely the case if you are following the 12 Factor app methodology.

    Unfortunately deis doesn't run the post-compile hooks in quite the same way Heroku does so we need to export our environment variables first. Using the sub-env function from the heroku-buildpack-python as a guide I came up with this...

    #!/usr/bin/env bash
    
    echo "-----> Running post-compile hook"
    
    BUILD_DIR=/tmp/build
    ENV_DIR=/tmp/environment
    
    BLACKLIST='^(GIT_DIR|STACK|PYTHONHOME|LD_LIBRARY_PATH|LIBRARY_PATH|PATH)$'
    
    # Python-specific variables.
    export PYTHONHOME=$BUILD_DIR/.heroku/python
    export PYTHONPATH=$BUILD_DIR/
    
    if [ -d "$ENV_DIR" ]; then
      for e in $(ls $ENV_DIR); do
        echo "$e" | grep -E "$WHITELIST" | grep -qvE "$BLACKLIST" &&
        export "$e=$(cat $ENV_DIR/$e)"
        :
      done
    fi
    
    $PYTHONHOME/bin/python manage.py migrate --noinput