Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,11 @@ There are a few ways to add a Python Project from the Python Environments panel:

#### Create New Project from Template

The **Python Envs: Create New Project from Template** command simplifies the process of starting a new Python project by scaffolding it for you. Whether in a new workspace or an existing one, this command configures the environment and boilerplate file structure, so you don’t have to worry about the initial setup, and only the code you want to write. There are currently two project types supported:
The **Python Envs: Create New Project from Template** command simplifies the process of starting a new Python project by scaffolding it for you. Whether in a new workspace or an existing one, this command configures the environment and boilerplate file structure, so you don’t have to worry about the initial setup, and only the code you want to write. There are currently three project types supported:

- Package: A structured Python package with files like `__init__.py` and setup configurations.
- Script: A simple project for standalone Python scripts, ideal for quick tasks or just to get you started.
- Django: A minimal Django project with `manage.py`, settings, URL configuration, and ASGI/WSGI entry points.

## Command Reference

Expand Down
19 changes: 19 additions & 0 deletions docs/managing-python-projects.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ Use this to scaffold a brand new Python project with the correct structure and f
3. Choose a template type:
- **Package**: A structured Python package with `pyproject.toml`, tests folder, and package directory
- **Script**: A simple standalone Python file using PEP 723 inline metadata
- **Django**: A minimal Django project with `manage.py`, settings, URL, and ASGI/WSGI modules
4. Enter a name for your project.
5. If you're creating a package, choose whether to create a virtual environment.

Expand All @@ -95,6 +96,24 @@ my_package_project/
└── __init__.py
```

#### Django template structure

When you create a Django project named `mysite`, the extension generates:

```
mysite_project/
├── manage.py
├── requirements.txt # Lists django; install it in the project's environment
└── mysite/ # The project package
├── __init__.py
├── asgi.py
├── settings.py # Includes a freshly generated SECRET_KEY
├── urls.py
└── wsgi.py
```

The project name must be a valid Python identifier and cannot be a Python keyword, `django`, or `test`. The extension does not create a virtual environment for Django projects; create one and run `pip install -r requirements.txt` before `python manage.py runserver`.

#### Script template

When you create a script, the extension generates a single `.py` file with PEP 723 inline script metadata, which allows you to specify dependencies directly in the file.
Expand Down
21 changes: 21 additions & 0 deletions files/templates/newDjangoTemplate/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == "__main__":
main()
Empty file.
8 changes: 8 additions & 0 deletions files/templates/newDjangoTemplate/project_name/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""ASGI config for project_name."""
import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")

application = get_asgi_application()
73 changes: 73 additions & 0 deletions files/templates/newDjangoTemplate/project_name/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Django settings for project_name."""
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# This key was generated when the project was created. Keep it secret in production.
SECRET_KEY = "django_secret_key"

# Turn DEBUG off and set ALLOWED_HOSTS before deploying.
DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "project_name.urls"

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

WSGI_APPLICATION = "project_name.wsgi.application"
ASGI_APPLICATION = "project_name.asgi.application"

DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}

AUTH_PASSWORD_VALIDATORS = [
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]

LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True

STATIC_URL = "static/"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
7 changes: 7 additions & 0 deletions files/templates/newDjangoTemplate/project_name/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""URL configuration for project_name."""
from django.contrib import admin
from django.urls import path

urlpatterns = [
path("admin/", admin.site.urls),
]
8 changes: 8 additions & 0 deletions files/templates/newDjangoTemplate/project_name/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""WSGI config for project_name."""
import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")

application = get_wsgi_application()
1 change: 1 addition & 0 deletions files/templates/newDjangoTemplate/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
django
5 changes: 5 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { getPythonApi, setPythonApi } from './extensionApi';
import { createManagerReady } from './features/common/managerReady';
import { AutoFindProjects } from './features/creators/autoFindProjects';
import { ExistingProjects } from './features/creators/existingProjects';
import { NewDjangoProject } from './features/creators/newDjangoProject';
import { NewPackageProject } from './features/creators/newPackageProject';
import { NewScriptProject } from './features/creators/newScriptProject';
import type { ProjectCreators } from './features/creators/projectCreators';
Expand Down Expand Up @@ -207,6 +208,7 @@ export async function activate(context: ExtensionContext): Promise<PythonEnviron
projectCreators.registerPythonProjectCreator(new AutoFindProjects(projectManager, envManagers)),
projectCreators.registerPythonProjectCreator(new NewPackageProject(envManagers, projectManager)),
projectCreators.registerPythonProjectCreator(new NewScriptProject(projectManager)),
projectCreators.registerPythonProjectCreator(new NewDjangoProject(projectManager)),
);

// Silent observer for `.py` files that declare PEP 723 inline
Expand Down Expand Up @@ -594,6 +596,9 @@ export async function activate(context: ExtensionContext): Promise<PythonEnviron
if (projectType === 'python-script') {
selected = creators.find((c) => c.name === 'newScript');
}
if (projectType === 'python-django') {
selected = creators.find((c) => c.name === 'newDjango');
}
if (!selected) {
throw new Error(`Project creator for type "${projectType}" not found.`);
}
Expand Down
162 changes: 162 additions & 0 deletions src/features/creators/newDjangoProject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import * as crypto from 'crypto';
import * as fs from 'fs-extra';
import * as path from 'path';
import { commands, l10n, MarkdownString, QuickInputButtons, Uri } from 'vscode';
import { PythonProject, PythonProjectCreator, PythonProjectCreatorOptions } from '../../api';
import { NEW_PROJECT_TEMPLATES_FOLDER } from '../../common/constants';
import { traceError } from '../../common/logging';
import { showErrorMessage, showInputBoxWithButtons, showTextDocument } from '../../common/window.apis';
import { getWorkspaceFolders } from '../../common/workspace.apis';
import type { PythonProjectManager } from '../projectManager';
import { replaceInFilesAndNames } from './creationHelpers';

// Names that cannot be used for the inner Django package: Python keywords would
// not import, 'django' or 'test' would shadow modules Django itself uses, and
// 'django_secret_key' is the placeholder the template fills with a generated key.
const RESERVED_DJANGO_PROJECT_NAMES = new Set([
'django',
'django_secret_key',
'test',
'False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield',
]);

export function validateDjangoProjectName(value: string): string | null {
// The name becomes an importable Python package, so it must be a plain identifier.
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
return l10n.t(
'Invalid project name. Use only letters, numbers, and underscores, and do not start with a number.',
);
}
if (RESERVED_DJANGO_PROJECT_NAMES.has(value)) {
return l10n.t('"{0}" cannot be used as a Django project name because it conflicts with a Python name.', value);
}
return null;
}

export class NewDjangoProject implements PythonProjectCreator {
public readonly name = l10n.t('newDjango');
public readonly displayName = l10n.t('Django');
public readonly description = l10n.t('Creates a Django project folder in your current workspace');
public readonly tooltip = new MarkdownString(l10n.t('Create a new Django project'));

constructor(private readonly projectManager: PythonProjectManager) {}

async create(options?: PythonProjectCreatorOptions): Promise<PythonProject | Uri | undefined> {
let projectName = options?.name;
if (!projectName) {
if (options?.quickCreate === true) {
throw new Error('Project name is required in quickCreate mode.');
}
try {
projectName = await showInputBoxWithButtons({
prompt: l10n.t('What is the name of the Django project? (e.g. mysite)'),
ignoreFocusOut: true,
showBackButton: true,
validateInput: validateDjangoProjectName,
});
} catch (ex) {
if (ex === QuickInputButtons.Back) {
await commands.executeCommand('python-envs.createNewProjectFromTemplate');
}
}
if (!projectName) {
return undefined;
}
}
const validationError = validateDjangoProjectName(projectName);
if (validationError) {
if (options?.quickCreate === true) {
throw new Error(validationError);
}
showErrorMessage(validationError);
return undefined;
}

// 1. Check the template and the destination
const templateFolder = path.join(NEW_PROJECT_TEMPLATES_FOLDER, 'newDjangoTemplate');
if (!(await fs.pathExists(templateFolder))) {
showErrorMessage(l10n.t('Template folder does not exist, aborting creation.'));
traceError(`Template folder not found at: ${templateFolder}`);
return undefined;
}

let destRoot = options?.rootUri?.fsPath;
if (!destRoot) {
const workspaceFolders = getWorkspaceFolders();
if (!workspaceFolders || workspaceFolders.length === 0) {
showErrorMessage(l10n.t('No workspace folder is open or provided, aborting creation.'));
return undefined;
}
destRoot = workspaceFolders[0].uri.fsPath;
}

const projectDestinationFolder = path.join(destRoot, `${projectName}_project`);
if (await fs.pathExists(projectDestinationFolder)) {
showErrorMessage(
l10n.t(
'A project folder by that name already exists, aborting creation. Please retry with a unique project name given your workspace.',
),
);
return undefined;
}

// 2. Copy the template and fill in the project name and a fresh secret key
const createdProject: PythonProject = {
name: projectName,
uri: Uri.file(projectDestinationFolder),
};
try {
await fs.copy(templateFolder, projectDestinationFolder);
await replaceInFilesAndNames(projectDestinationFolder, 'project_name', projectName);
// Hex only, so the key is safe to use as a regular expression replacement value.
const secretKey = `django-insecure-${crypto.randomBytes(25).toString('hex')}`;
await replaceInFilesAndNames(projectDestinationFolder, 'django_secret_key', secretKey);
await this.projectManager.add(createdProject);
} catch (creationError) {
try {
await fs.remove(projectDestinationFolder);
} catch (rollbackError) {
traceError('Failed to delete the new Django project after creation failed:', rollbackError);
}
throw creationError;
}

await showTextDocument(Uri.file(path.join(projectDestinationFolder, 'manage.py')));

return createdProject;
}
}
Loading