The Django shell is a powerful development tool. Comes in handy when you want to try operations without having to hit REST endpoints or access pages.
As trend to containerize projects continues, you will find yourself needing visibility into what's going on in your Django code inside a container.
Not to worry, the Django shell is available in the container. Let's see how to get to it.
Suppose you have a docker-compose file looking something like:
services:
# Django web server
web:
image: web:local
build:
context: ./django
dockerfile: Dockerfile
hostname: web
volumes:
- ./django:/app
To get a shell in a container, we use
docker exec -it <name_or_id> /bin/sh
can be the container id which is a cryptic string or the name which is the form of 'folder-servicename-number'. So for this project, we use:
docker exec -it folder-web-1 /bin/sh
/app #
Great so I have a shell in the container, now we want to start the django shell:
/app # ./manage.py shell
Pretty simple.
If the folder name is long or we don't know the number attached, we can use the name given in the docker compose file to find the id.
docker ps --filter ancestor=web:local --format "{{.ID}}"
32930efb8133
Now you copy and paste the id into the docker exec command
docker exec -it 32930efb8133 /bin/sh
/app #
If you want a one-liner:
docker exec -it $(docker ps --filter ancestor=web:local --format "{{.ID}}") /bin/sh
Have any tips you want to add, put in the comments below.
Thanks!