feat(python): set Django up in the Python Console of a Django project (#6543)

In a Django project the Python Console started a plain interpreter, so importing models failed with ImproperlyConfigured. When the project's manage.py sets DJANGO_SETTINGS_MODULE, the console now starts in manage.py's directory and its driver calls django.setup() with that settings module (one already in the environment wins, as for manage.py). On Django 5.2+ it also defines what manage.py shell imports automatically (the models, settings, timezone, ...) and keeps those names out of the Variables pane. The header shows the Django version; if setup fails, the traceback is printed and the console works as before.

Closes #6536

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-28 01:51:13 +08:00
1 джерело 382c22cfc3
коміт 10b459268e
5 files changed
+80 -8

No files matched your search

+24 -1
Переглянути файл
@@ -2,6 +2,7 @@
# runs it in IPython when installed, else in a plain namespace, and after each run writes
# a record-separator line (\x1e + JSON) with the console's variables.
import json
import os
import reprlib
import sys
import textwrap
@@ -80,7 +81,29 @@ except ImportError:
_console.showtraceback()
_send({"ready": {"version": sys.version.split()[0], "ipython": flavour}})
ready = {"version": sys.version.split()[0], "ipython": flavour}
# A Django project (PyCharm's Django Console): set Django up and import what `manage.py shell` does.
if os.environ.get("OPENIDEA_DJANGO_SETTINGS"):
if not os.environ.get("DJANGO_SETTINGS_MODULE"): # as manage.py: the environment's own wins
os.environ["DJANGO_SETTINGS_MODULE"] = os.environ["OPENIDEA_DJANGO_SETTINGS"]
try:
import django
django.setup()
ready["django"] = django.get_version()
try:
from django.core.management.commands.shell import Command
imports = Command().get_namespace() # Django 5.2+: the models and common utilities
except Exception:
imports = {}
namespace.update(imports)
_hidden.update(imports)
except Exception:
import traceback
traceback.print_exc()
_send({"ready": ready})
while True:
line = sys.stdin.readline()
if not line: