The Django Shell
The Django shell is a Python prompt with the project loaded. It runs one line at a time for trying things out.
Start the shell
This command opens the shell. The lines below it are the real session.
$ python manage.py shell
>>> from blog.models import Post
>>> post = Post(title="First post", body="Hello from Django.")
>>> post.title
'First post'Read the body back
One more line reads the body of the same post.
>>> post.body
'Hello from Django.'Leave the shell
The exit call closes the shell and returns to the terminal.
>>> exit()Example
import django
from django.conf import settings
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
INSTALLED_APPS=[
"django.contrib.contenttypes",
"django.contrib.auth",
],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()
from django.db import connection, models
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Meta:
app_label = "blog"
with connection.schema_editor() as editor:
editor.create_model(Post)
post = Post(title="First post", body="Hello from Django.")
print(post.title)
print(post.body)
Key points
- Start the shell with python manage.py shell.
- The shell loads the project before the first prompt.
- Type a model line and read the answer at once.
- The >>> mark is the shell prompt.
- The shell loads the project, but you import the models yourself.
- Quit the shell with exit().
In this example, the program repeats the lines of the shell session. The setup lines configure Django. The program creates the table directly. A real project uses migrations for this step. The last lines make one post and print its title and body.
Note
Lines typed in the shell run once. They are not saved as a file.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How do you start the Django shell?