From 10b459268e0350a2909cdff821e03c41eff927f4 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sat, 28 Nov 2026 02:51:13 +0900 Subject: [PATCH] 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 <26499420+wildcatDownstairs@users.noreply.github.com> --- src/features/python-console/console.py | 25 +++++++++++++++++++- src/features/python-console/console.test.ts | 26 +++++++++++++++++++++ src/features/python-console/protocol.ts | 2 +- src/features/python-console/store.test.ts | 10 +++++++- src/features/python-console/store.ts | 25 ++++++++++++++++---- 5 files changed, 80 insertions(+), 8 deletions(-) diff --git a/src/features/python-console/console.py b/src/features/python-console/console.py index 0cdb7cdc6..c04cbaf46 100644 --- a/src/features/python-console/console.py +++ b/src/features/python-console/console.py @@ -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: diff --git a/src/features/python-console/console.test.ts b/src/features/python-console/console.test.ts index 9c519da7f..b71934d4f 100644 --- a/src/features/python-console/console.test.ts +++ b/src/features/python-console/console.test.ts @@ -1,5 +1,8 @@ // @vitest-environment node import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { expect, it } from "vitest"; import { request, stdoutParser, type ConsoleMessage } from "./protocol"; @@ -9,6 +12,8 @@ const PYTHON = ["python3", "python"].find((p) => spawnSync(p, ["--version"]).sta // An interpreter with IPython, for the IPython path (OPENIDEA_TEST_IPYTHON, else none: skipped). const IPYTHON = process.env.OPENIDEA_TEST_IPYTHON; +// An interpreter with Django 5.2+, for the Django console (OPENIDEA_TEST_DJANGO, else none: skipped). +const DJANGO = process.env.OPENIDEA_TEST_DJANGO; function run(codes: string[], input = "", python = PYTHON!) { const stdin = codes.map(request).join("") + input; @@ -65,3 +70,24 @@ it.skipIf(!IPYTHON)("ends at exit() under IPython", () => { expect(messages[0]).toEqual({ ready: { version: expect.any(String), ipython: expect.stringMatching(/^IPython /) } }); expect([text, messages.length, status]).toEqual(["", 2, 0]); }); + +it.skipIf(!DJANGO)("sets Django up and imports the models like manage.py shell", () => { + const cwd = mkdtempSync(join(tmpdir(), "console-django-")); + writeFileSync( + join(cwd, "site_settings.py"), + 'SECRET_KEY = "x"\nINSTALLED_APPS = ["django.contrib.contenttypes", "django.contrib.auth"]\n' + + 'DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}\n', + ); + // As the IDE runs it: `-c`, so the working directory (manage.py's) is on sys.path. + const result = spawnSync(DJANGO!, ["-u", "-c", readFileSync(DRIVER, "utf8")], { + cwd, + input: request("User._meta.label, settings.SECRET_KEY"), + encoding: "utf8", + env: { ...process.env, OPENIDEA_DJANGO_SETTINGS: "site_settings", DJANGO_SETTINGS_MODULE: "" }, + }); + const { text, messages } = stdoutParser()(result.stdout); + expect(messages[0]).toMatchObject({ ready: { django: expect.stringMatching(/^\d/) } }); + expect(text).toContain("('auth.User', 'x')"); + // The imports are the console's own, not the user's variables. + expect(variables(messages)[0]).toEqual([]); +}); diff --git a/src/features/python-console/protocol.ts b/src/features/python-console/protocol.ts index cf2eb093b..2e0fe0e38 100644 --- a/src/features/python-console/protocol.ts +++ b/src/features/python-console/protocol.ts @@ -3,7 +3,7 @@ export type ConsoleVariable = { name: string; type: string; value: string }; export type ConsoleMessage = - | { ready: { version: string; ipython: string | null } } + | { ready: { version: string; ipython: string | null; django?: string } } | { done: { variables: ConsoleVariable[] } }; const RS = "\x1e"; diff --git a/src/features/python-console/store.test.ts b/src/features/python-console/store.test.ts index 0b75bde18..df27b6e6c 100644 --- a/src/features/python-console/store.test.ts +++ b/src/features/python-console/store.test.ts @@ -26,6 +26,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => { commands: { runList: () => Promise.resolve([]), sdkPythonEffective: () => ok("/venv/bin/python"), + findFilesNamed: () => ok([]), runStart: (_config: unknown, channel: NonNullable["channel"]) => new Promise((resolve) => { ipc.started = { channel, resolve: (id) => resolve({ status: "ok", data: { id } }) }; @@ -39,7 +40,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => { }; }); -const { execute, installConsole, stopConsole, tail, useConsole } = await import("./store"); +const { execute, installConsole, settingsModule, stopConsole, tail, useConsole } = await import("./store"); const { request } = await import("./protocol"); const settle = () => new Promise((r) => setTimeout(r, 0)); const text = () => @@ -83,3 +84,10 @@ it("keeps the newest output within the cap, cutting into the oldest kept span", expect(tail(spans, 5)).toEqual([{ text: "a" }, { text: "bb", fg: "red" }, { text: "cc" }]); expect(tail(spans, 3)).toEqual([{ text: "b", fg: "red" }, { text: "cc" }]); }); + +it("reads the settings module manage.py sets", () => { + expect(settingsModule(` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")`)).toBe( + "config.settings", + ); + expect(settingsModule("print('hi')")).toBeNull(); +}); diff --git a/src/features/python-console/store.ts b/src/features/python-console/store.ts index a4ac9d408..690384218 100644 --- a/src/features/python-console/store.ts +++ b/src/features/python-console/store.ts @@ -1,6 +1,7 @@ /** The Python Console's process: the project interpreter running console.py on the Run process host. */ import { Channel } from "@tauri-apps/api/core"; import { create } from "zustand"; +import { pickManage } from "@/features/django/manage"; import { call, commands, onIdeEvent, type OutputChunk, type RunConfig, type RunId } from "@/platform/ipc"; import { windowLabel } from "@/platform/auxWindow"; import { dirname, useProject } from "@/platform/project"; @@ -75,8 +76,9 @@ function next() { function onMessage(message: ConsoleMessage) { if ("ready" in message) { - const { version, ipython } = message.ready; - useConsole.setState({ header: ipython ? `Python ${version} (${ipython})` : `Python ${version}`, status: "idle" }); + const { version, ipython, django } = message.ready; + const extras = [ipython, django && `Django ${django}`].filter(Boolean).join(", "); + useConsole.setState({ header: extras ? `Python ${version} (${extras})` : `Python ${version}`, status: "idle" }); } else { useConsole.setState({ variables: message.done.variables, status: "idle" }); } @@ -86,7 +88,18 @@ function onMessage(message: ConsoleMessage) { /** Run ids of this window's consoles: a reloaded page finds the ones its previous load left running. */ const PREFIX = `python-console:${windowLabel()}:`; -function config(python: string, cwd: string): RunConfig { +/** The settings module `manage.py` sets as DJANGO_SETTINGS_MODULE. */ +export const settingsModule = (manage: string) => + /DJANGO_SETTINGS_MODULE["']\s*,\s*["']([\w.]+)["']/.exec(manage)?.[1] ?? null; + +/** In a Django project the console runs where manage.py is, with Django set up (PyCharm's Django Console). */ +async function django(): Promise<{ cwd: string; settings: string } | null> { + const manage = pickManage((await call(commands.findFilesNamed("manage.py")).catch(() => [])).map(String)); + const settings = manage && settingsModule((await call(commands.fsReadText(manage)).catch(() => null)) ?? ""); + return manage && settings ? { cwd: dirname(manage), settings } : null; +} + +function config(python: string, cwd: string, settings?: string): RunConfig { return { id: `${PREFIX}${crypto.randomUUID()}`, name: "Python Console", @@ -95,7 +108,7 @@ function config(python: string, cwd: string): RunConfig { command: python, args: ["-u", "-c", DRIVER], cwd, - env: {}, + env: settings ? { OPENIDEA_DJANGO_SETTINGS: settings } : {}, detected: true, isTest: false, debugAdapter: null, @@ -135,7 +148,9 @@ export async function startConsole() { } // "system" chunks echo the command line, which is the driver's source here. }; - const info = await call(commands.runStart(config(python, root), channel, null)); + const site = await django(); + if (mine !== generation) return; + const info = await call(commands.runStart(config(python, site?.cwd ?? root, site?.settings), channel, null)); if (mine !== generation) void call(commands.runStop(info.id)).catch(() => {}); else { runId = info.id;