DEV Community

Cover image for You don't have to type all your manage.py or django-admin commands by hand anymore! Here's Django command auto complete hack
Ratul Roy
Ratul Roy

Posted on

You don't have to type all your manage.py or django-admin commands by hand anymore! Here's Django command auto complete hack

If you're like me then you love the terminal and everything about it. One thing that make the terminal experiences smooth is the Tab button autocomplete. Writing recognizable amount of the command or it's parameters and hitting Tab saves me a lot of time. But in the case of django I had to spell out runserver or makemigrations every time I initiated a dev server.
Alt Text
So I've enable Django commands auto complete and here's how you can do it too.
open up your .bashrc file with your favorite text editor. You'll find it at ~/.bashrc. Then add the following at the end of your file

# Django autocomplete start
_django_completion()
{
    COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \
                   COMP_CWORD=$COMP_CWORD \
                   DJANGO_AUTO_COMPLETE=1 $1 ) )
}
complete -F _django_completion -o default manage.py django-admin

_python_django_completion()
{
    if [[ ${COMP_CWORD} -ge 2 ]]; then
        local PYTHON_EXE=${COMP_WORDS[0]##*/}
        if echo "$PYTHON_EXE" | grep -qE "python([3-9]\.[0-9])?"; then
            local PYTHON_SCRIPT=${COMP_WORDS[1]##*/}
            if echo "$PYTHON_SCRIPT" | grep -qE "manage\.py|django-admin"; then
                COMPREPLY=( $( COMP_WORDS=( "${COMP_WORDS[*]:1}" )
                               COMP_CWORD=$(( COMP_CWORD-1 ))
                               DJANGO_AUTO_COMPLETE=1 ${COMP_WORDS[*]} ) )
            fi
        fi
    fi
}

# Support for multiple interpreters.
unset pythons
if command -v whereis &>/dev/null; then
    python_interpreters=$(whereis python | cut -d " " -f 2-)
    for python in $python_interpreters; do
        [[ $python != *-config ]] && pythons="${pythons} ${python##*/}"
    done
    unset python_interpreters
    pythons=$(echo "$pythons" | tr " " "\n" | sort -u | tr "\n" " ")
else
    pythons=python
fi

complete -F _python_django_completion -o default $pythons
unset pythons

# Django autocomplete end
Enter fullscreen mode Exit fullscreen mode

Save the file and you're all done! And yes it was THIS EASY! To work at your already opened terminal just type reset and enter. Or source ~/.bashrc would do the trick too!

Top comments (3)

Collapse
 
phase_seven profile image
Ratul Roy

The code snippet is taken from this repository

Collapse
 
shahedex profile image
Shahed Mehbub

Good one 👍

Collapse
 
phase_seven profile image
Ratul Roy

Thanks! And welcome to Dev.to