If you’re anything like me, you probably write Python every day and occasionally pop open a quick interactive shell to test a snippet or inspect a model. My Django project was running perfectly fine through manage.py
, but when I opened a plain Python interpreter and tried this:
from django.contrib.auth.models import User
Boom. Full-blown traceback explosion:
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES,
but settings are not configured. You must either define the environment
variable DJANGO_SETTINGS_MODULE or call settings.configure()
before accessing settings.
At first glance, it feels like Django has completely forgotten how to read its own settings. But don’t panic—the problem isn’t actually with your database settings. It’s just Django being Django.
Why This Error Happen
Django only loads settings.py
automatically when you use commands like:
python manage.py runserver
python manage.py shell
But when I opened a plain Python interpreter using:
python3
Django had no clue which settings module to use—so the moment I tried importing a model, it crashed.
Use manage.py shell
Instead of launching a bare Python shell, I use Django’s built-in shell which preloads all configurations:
python manage.py shell
Now everything behaves exactly as expected:
from django.contrib.auth.models import User
User.objects.all()
Manually Configure Django in a Raw Python Shell
If for some reason I must stay inside a plain python3
session (for example, inside a script), I manually configure Django before importing anything model-related:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")
import django
django.setup()
from django.contrib.auth.models import User
print(User.objects.all())
Replace "your_project_name.settings"
with the actual path to your settings module.
Practice Time: Create and Query a User
Once Django is properly configured, I love testing quick database interactions like this:
# Create a new user
user = User.objects.create_user(username="alice", email="alice@example.com", password="secret123")
# Fetch all users
for u in User.objects.all():
print(u.username, "-", u.email)
# Filter users
admins = User.objects.filter(is_staff=True)
print("Admin users:", admins)
Final Thought
At the end of the day, this error isn’t a sign of broken settings it’s just Django waiting for proper instructions. Once I understood that Django doesn’t automatically know which configuration to use outside of manage.py
, everything clicked. Whether I’m inside manage.py shell
or manually calling django.setup()
, I now have full control over when and how my Django environment loads. A small fix but a huge difference in productivity.