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:
+26
Переглянути файл
@@ -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([]);
});
+1 -1
Переглянути файл
@@ -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";
+9 -1
Переглянути файл
@@ -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<typeof ipc.started>["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();
});
+20 -5
Переглянути файл
@@ -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;