дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
fix(python): address the review of the Django PRs #6542-#6545 (#6656)
Follow-up fixes to the Django support: - manage.py tasks: manage.py is looked up on each use and only a successful command list is cached; lines run while help loads go to manage.py; a failed help is reported; the active file's project picks the manage.py in a monorepo (shared via platform/django.ts); py/python3.x/Windows forms count as manage.py lines. - Django console: keeps the project root as working directory with manage.py's folder on sys.path, reads setdefault and os.environ[...] settings forms, and shows auto-imported names once reassigned. - URL names: re-reading names clears navigation's cache, names nest under include namespaces, and only path/re_path/url name= counts (small Python scanner). - Field lookups: models keyed per app, multi-table inheritance reverse names fixed, related_query_name/related_name/%(class)s rules, relation lookups and <fk>_id, completion in Q(...) and after F(...). Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
1 джерело
68abd00a7f
коміт
9d92f47f94
19 files changed
+1158
-262
No files matched your search
@@ -27,6 +27,8 @@ def _variables(namespace):
|
||||
for name, value in list(namespace.items()):
|
||||
if name.startswith("_") or name in _hidden or isinstance(value, types.ModuleType):
|
||||
continue
|
||||
if name in _auto and _auto[name] is value:
|
||||
continue
|
||||
try:
|
||||
text = _repr.repr(value)
|
||||
except Exception as error: # a broken __repr__ must not break the console
|
||||
@@ -82,10 +84,15 @@ except ImportError:
|
||||
|
||||
|
||||
ready = {"version": sys.version.split()[0], "ipython": flavour}
|
||||
# Names `manage.py shell` imports, hidden from the variables while they keep their value.
|
||||
_auto = {}
|
||||
# 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"]
|
||||
if os.environ.get("OPENIDEA_DJANGO_DIR"):
|
||||
if os.environ["OPENIDEA_DJANGO_DIR"] not in sys.path:
|
||||
sys.path.insert(0, os.environ["OPENIDEA_DJANGO_DIR"]) # where manage.py imports the settings from
|
||||
if not os.environ.get("DJANGO_SETTINGS_MODULE") and os.environ.get("OPENIDEA_DJANGO_SETTINGS"):
|
||||
os.environ["DJANGO_SETTINGS_MODULE"] = os.environ["OPENIDEA_DJANGO_SETTINGS"] # as manage.py: the environment's wins
|
||||
if os.environ.get("OPENIDEA_DJANGO_DIR") and os.environ.get("DJANGO_SETTINGS_MODULE"):
|
||||
try:
|
||||
import django
|
||||
|
||||
@@ -94,11 +101,11 @@ if os.environ.get("OPENIDEA_DJANGO_SETTINGS"):
|
||||
try:
|
||||
from django.core.management.commands.shell import Command
|
||||
|
||||
imports = Command().get_namespace() # Django 5.2+: the models and common utilities
|
||||
# Django 5.2+: the models; 6.0+ also settings, timezone, models, functions…
|
||||
_auto = Command().get_namespace()
|
||||
except Exception:
|
||||
imports = {}
|
||||
namespace.update(imports)
|
||||
_hidden.update(imports)
|
||||
pass
|
||||
namespace.update(_auto)
|
||||
except Exception:
|
||||
import traceback
|
||||
|
||||
|
||||
@@ -71,23 +71,62 @@ it.skipIf(!IPYTHON)("ends at exit() under 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([]);
|
||||
});
|
||||
it.skipIf(!DJANGO)(
|
||||
"sets Django up and imports the models like manage.py shell",
|
||||
() => {
|
||||
const site = mkdtempSync(join(tmpdir(), "console-django-"));
|
||||
writeFileSync(
|
||||
join(site, "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`, in the project root, with manage.py's folder given apart.
|
||||
const result = spawnSync(DJANGO!, ["-u", "-c", readFileSync(DRIVER, "utf8")], {
|
||||
cwd: tmpdir(),
|
||||
input: [
|
||||
"User._meta.label",
|
||||
"import django\ndjango.VERSION >= (6,) and settings.SECRET_KEY",
|
||||
"x = 1",
|
||||
"User = 'mine'",
|
||||
]
|
||||
.map(request)
|
||||
.join(""),
|
||||
encoding: "utf8",
|
||||
env: {
|
||||
...process.env,
|
||||
OPENIDEA_DJANGO_DIR: site,
|
||||
OPENIDEA_DJANGO_SETTINGS: "site_settings",
|
||||
DJANGO_SETTINGS_MODULE: "",
|
||||
},
|
||||
});
|
||||
const { text, messages } = stdoutParser()(result.stdout);
|
||||
expect(result.stderr).toBe("");
|
||||
expect(messages[0]).toMatchObject({ ready: { django: expect.stringMatching(/^\d/) } });
|
||||
// 5.2+ imports the models; 6.0+ also `settings` (False on 5.2).
|
||||
expect(text).toMatch(/^'auth\.User'\n('x'|False)\n/);
|
||||
// The imports are the console's own, not the user's variables, until the user assigns one.
|
||||
expect(variables(messages)[2]).toEqual(["x: int = 1"]);
|
||||
expect(variables(messages)[3]).toEqual(["User: str = 'mine'", "x: int = 1"]);
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
|
||||
it.skipIf(!DJANGO)(
|
||||
"uses DJANGO_SETTINGS_MODULE from the environment when manage.py names none",
|
||||
() => {
|
||||
const site = mkdtempSync(join(tmpdir(), "console-django-"));
|
||||
writeFileSync(join(site, "env_settings.py"), 'SECRET_KEY = "x"\nINSTALLED_APPS = []\n');
|
||||
const ready = (env: Record<string, string>) => {
|
||||
const result = spawnSync(DJANGO!, ["-u", "-c", readFileSync(DRIVER, "utf8")], {
|
||||
cwd: tmpdir(),
|
||||
input: "",
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, OPENIDEA_DJANGO_DIR: site, ...env },
|
||||
});
|
||||
return stdoutParser()(result.stdout).messages[0];
|
||||
};
|
||||
expect(ready({ DJANGO_SETTINGS_MODULE: "env_settings" })).toMatchObject({ ready: { django: expect.any(String) } });
|
||||
expect(ready({ DJANGO_SETTINGS_MODULE: "" })).not.toHaveProperty("ready.django");
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
@@ -89,5 +89,12 @@ it("reads the settings module manage.py sets", () => {
|
||||
expect(settingsModule(` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")`)).toBe(
|
||||
"config.settings",
|
||||
);
|
||||
expect(settingsModule(`os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings'`)).toBe("site.settings");
|
||||
expect(
|
||||
settingsModule(
|
||||
`# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "old")\nos.environ.setdefault("DJANGO_SETTINGS_MODULE", "new")`,
|
||||
),
|
||||
).toBe("new");
|
||||
expect(settingsModule(`os.environ.setdefault("DJANGO_SETTINGS_MODULE", f"{SITE}.settings")`)).toBeNull();
|
||||
expect(settingsModule("print('hi')")).toBeNull();
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
/** 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 { findManage } from "@/platform/django";
|
||||
import { dirname, useProject } from "@/platform/project";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { AnsiStream, appendSpans, type Span } from "@/ui/ansi";
|
||||
@@ -88,18 +88,20 @@ 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()}:`;
|
||||
|
||||
/** The settings module `manage.py` sets as DJANGO_SETTINGS_MODULE. */
|
||||
/** The settings module `manage.py` sets as DJANGO_SETTINGS_MODULE (`setdefault(…)` or `os.environ[…] =`). */
|
||||
export const settingsModule = (manage: string) =>
|
||||
/DJANGO_SETTINGS_MODULE["']\s*,\s*["']([\w.]+)["']/.exec(manage)?.[1] ?? null;
|
||||
/^[^#\n]*DJANGO_SETTINGS_MODULE["']\s*(?:,|\]\s*=)\s*["']([\w.]+)["']/m.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;
|
||||
/** Environment that has the driver set Django up (PyCharm's Django Console), in a project with a manage.py. */
|
||||
async function djangoEnv(near: string | null): Promise<Record<string, string>> {
|
||||
const manage = await findManage(near).catch(() => null);
|
||||
if (!manage) return {};
|
||||
const settings = settingsModule((await call(commands.fsReadText(manage)).catch(() => null)) ?? "");
|
||||
// Without a literal settings module, Django is set up only if the environment names one.
|
||||
return { OPENIDEA_DJANGO_DIR: dirname(manage), ...(settings && { OPENIDEA_DJANGO_SETTINGS: settings }) };
|
||||
}
|
||||
|
||||
function config(python: string, cwd: string, settings?: string): RunConfig {
|
||||
function config(python: string, cwd: string, env: Record<string, string>): RunConfig {
|
||||
return {
|
||||
id: `${PREFIX}${crypto.randomUUID()}`,
|
||||
name: "Python Console",
|
||||
@@ -108,7 +110,7 @@ function config(python: string, cwd: string, settings?: string): RunConfig {
|
||||
command: python,
|
||||
args: ["-u", "-c", DRIVER],
|
||||
cwd,
|
||||
env: settings ? { OPENIDEA_DJANGO_SETTINGS: settings } : {},
|
||||
env,
|
||||
detected: true,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
@@ -148,9 +150,9 @@ export async function startConsole() {
|
||||
}
|
||||
// "system" chunks echo the command line, which is the driver's source here.
|
||||
};
|
||||
const site = await django();
|
||||
const env = await djangoEnv(active);
|
||||
if (mine !== generation) return;
|
||||
const info = await call(commands.runStart(config(python, site?.cwd ?? root, site?.settings), channel, null));
|
||||
const info = await call(commands.runStart(config(python, root, env), channel, null));
|
||||
if (mine !== generation) void call(commands.runStop(info.id)).catch(() => {});
|
||||
else {
|
||||
runId = info.id;
|
||||
|
||||
Reference in new issue
Заблокувати користувача