How the Playground Runs Django
A real Django project is a folder of files: settings.py, urls.py, one or more apps, a database file and a server process. A playground on this site is just one Python file that runs in your browser (CPython compiled to WebAssembly, with real Django 5.2 installed on the fly). So every example squeezes the project into a few lines of setup. You'll see this setup at the top of nearly every example — read it once here and you can skim it from now on.
The setup template
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls") # stands in for urls.py
settings.configure( # stands in for settings.py
SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}],
)
django.setup() # load apps, like manage.py doesLine by line:
| Code | Real-project equivalent |
|---|---|
settings.configure(...) |
the settings.py module (normally found through DJANGO_SETTINGS_MODULE) |
SECRET_KEY="demo" |
the secret used for signing cookies and tokens — never use a short one in production |
types.ModuleType("urls") + ROOT_URLCONF="urls" |
the project's urls.py; we create an empty module and later set urls.urlpatterns = [...] |
ALLOWED_HOSTS=["testserver"] |
the domain names the site answers to; testserver is the host the test client uses |
"NAME": ":memory:" |
db.sqlite3 — but kept in memory, so every run starts empty |
TEMPLATES=[...] |
the template engine configuration |
django.setup() |
what manage.py and wsgi.py do at start-up: populate the app registry |
Examples only include the settings they need. A template-only example might call settings.configure(TEMPLATES=[...]) and nothing else.
Note:
settings.configure()anddjango.setup()can only run once per Python process. The playground starts a fresh interpreter for each run, so that's never a problem here.
Models without an app folder
In a project, models live in <app>/models.py and Django infers which app they belong to from the folder. A playground has no app folder, so every model says it explicitly:
class Meta:
app_label = "demo"The table is then named demo_<model>, exactly as if the model lived in an app called demo.
Tables without migrations
In a project you run makemigrations and migrate to create tables. Migration files need an app folder on disk, so the playground creates tables directly with the schema editor — the same low-level tool migrations use internally:
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
class Note(models.Model):
text = models.CharField(max_length=200)
class Meta:
app_label = "demo"
print("Before:", connection.introspection.table_names())
with connection.schema_editor() as editor:
editor.create_model(Note)
print("After: ", connection.introspection.table_names())
Note.objects.create(text="Fresh database every run")
print(Note.objects.get(pk=1).text)Before: []
After: ['demo_note']
Fresh database every run
When models are related
app_label alone is enough for single models. But Django only discovers reverse relations — author.posts, cascading deletes, Count("posts") — for models of installed apps. So examples with ForeignKey or ManyToManyField also install a stand-in demo app: an empty module placed in sys.modules, listed in INSTALLED_APPS:
sys.modules["demo"] = types.ModuleType("demo") # stand-in for a demo/ app package
sys.modules["demo"].__file__ = "demo/__init__.py"
settings.configure(INSTALLED_APPS=["demo"], ...)In a project, INSTALLED_APPS = [..., "demo"] pointing at a real folder does the same job.
When an example needs Django's own tables (users, sessions …) it runs the real migrations with call_command("migrate", verbosity=0).
Requests without a server
There is no web server in the browser, but Django ships one testing tool that's perfect here: the test client. Client().get("/path/") builds a request, passes it through the URLconf, middleware and view, and hands back the response object — exactly what a browser would have received.
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client
def greet(request, name):
return HttpResponse(f"Hi, {name}!", content_type="text/plain")
urls.urlpatterns = [path("greet/<str:name>/", greet)]
client = Client()
r = client.get("/greet/Linh/")
print(r.status_code, r["Content-Type"])
print(r.content.decode())
print(client.get("/missing/").status_code)200 text/plain
Hi, Linh!
404
| Response attribute | Meaning |
|---|---|
r.status_code |
HTTP status, e.g. 200, 302, 404 |
r.content |
body as bytes — use .decode() for text |
r["Header-Name"] |
a response header |
r.json() |
parse a JSON body |
Putting it all together
Model + view + URL + test client in one file — the shape of most examples in this course:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
from django.http import HttpResponse
from django.urls import path
from django.test import Client
class Task(models.Model):
title = models.CharField(max_length=100)
done = models.BooleanField(default=False)
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Task)
Task.objects.create(title="Learn views")
Task.objects.create(title="Learn models", done=True)
def task_list(request):
lines = [f"[{'x' if t.done else ' '}] {t.title}" for t in Task.objects.order_by("id")]
return HttpResponse("\n".join(lines))
urls.urlpatterns = [path("tasks/", task_list)]
print(Client().get("/tasks/").content.decode())[ ] Learn views
[x] Learn models
Tip: Output must be predictable, so examples sort query results with
order_by()and avoid the current time. In your own projects you're free to use both.
Test yourself
What replaces settings.py in a playground example?
django.setup()settings.configure(...)call_command("migrate")Client()
Why does every playground model declare app_label = "demo"?
- To make it faster
- Because the model is not inside an app folder, so Django can't infer its app
- To give the table a primary key
- It is required for all Django models
How do examples send HTTP requests without a server?
- With
urllib - With
django.test.Client - With
runserver - They can't