Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:46:40 +08:00
commit 66f1bf4fb0
33 changed files with 6059 additions and 0 deletions

View File

@@ -0,0 +1,144 @@
# Django Setup Skill (HTTPS Development)
**For HTTPS-only Django projects using mkcert SSL certificates.**
## Skill Overview
This skill sets up Django projects specifically for **HTTPS local development**, which is required for:
- WebAuthn/Passkeys (MFA)
- Secure cookies
- Service workers
- Modern browser APIs
## Key Features
-**Automatic Python version selection** - Uses highest available 3.8-3.13, installs 3.13 if none found
-**HTTPS by default** - Integrated mkcert setup
-**Core dependencies** - Django, python-dotenv, djangorestframework, django-cors-headers; adds `uvicorn[standard]` for SSL serving
-**Uvicorn ASGI server** - With SSL support
-**Manual, guided setup** - No automation scripts, full control
## Progressive Disclosure Structure
```
django-setup/
├── SKILL.md # ⭐ Core skill (HTTPS-focused)
├── README.md # This file
├── platform-https/ # 🔒 mkcert + Uvicorn setup per OS
│ ├── mkcert-https-setup-macos.md
│ ├── mkcert-https-setup-linux.md
│ └── mkcert-https-setup-windows.md
├── platform-install/ # 📦 Platform-specific Python installation
│ ├── macos.md
│ ├── linux-ubuntu.md
│ ├── linux-fedora.md
│ └── windows.md
├── troubleshooting/ # 🔧 Problem-solving guides
│ ├── venv-issues.md
│ ├── pip-problems.md
│ └── django-errors.md
└── examples/ # 📋 Templates
└── .gitignore-template
```
## What's Different from Standard Django Setup?
| Standard Django | This Skill |
|----------------|------------|
| HTTP only (port 8000) | HTTPS with mkcert |
| `python manage.py runserver` | `./run.sh` / `run.bat` (Uvicorn with SSL) |
| No SSL certificates | SSL certs in `certs/` |
| Optional HTTPS | HTTPS required |
| Any dependencies | Focused: Django, dotenv, DRF, django-cors-headers + uvicorn |
## Quick Setup Flow
1. **Check/install Python 3.8-3.13** (uses highest, installs 3.13 if needed)
2. **Create venv** with selected Python version
3. **Install core dependencies** (Django, python-dotenv, djangorestframework, django-cors-headers)
4. **Create Django project** (`django-admin startproject backend .`)
5. **Set up mkcert HTTPS + Uvicorn** (platform-https guides install `uvicorn[standard]`, generate certs, create run script)
6. **Configure settings.py for CORS/CSRF** (adds corsheaders middleware & allowed origins)
7. **Add health + CSRF helper endpoints** (`api/health`, `api/csrf`)
8. **Run migrations** (`python manage.py migrate`)
9. **Optional VS Code launch config** (`.vscode/launch.json`)
10. **Test with HTTPS** (`./run.sh` or `run.bat``https://localhost:8000`)
## Why These Dependencies?
Authentication packages (allauth, etc.) are **intentionally excluded** and should be added later via the `django-allauth-config` skill to keep the base setup lean. `django-cors-headers` is included because the skill configures CORS/CSRF for a typical HTTPS frontend, and `uvicorn[standard]` is used to serve Django over SSL in development.
**Core dependencies:**
```bash
pip install Django python-dotenv djangorestframework django-cors-headers
```
**HTTPS server:**
```bash
pip install 'uvicorn[standard]'
```
**Add authentication later:**
```bash
# Use django-allauth-config skill
pip install django-allauth[socialaccount,mfa] django-cors-headers
```
## Integration with Other Skills
This skill integrates with:
- **mkcert-https-setup** - SSL certificate setup (referenced inline via platform-https guides)
- **django-allauth-config** - Add authentication after base setup
## Token Efficiency
**Core SKILL.md:** ~2,500 tokens (HTTPS-focused, no automation)
**Platform guides:** ~400-600 tokens (loaded only when needed)
**Troubleshooting:** ~300-500 tokens (loaded only on errors)
**Average context usage:** ~2,800 tokens
**Compared to v1.0 monolithic:** 65% reduction
## Usage
```bash
# User says: "Set up Django project for HTTPS"
# Claude loads: django-project-setup skill
# Guides through: Python → venv → Django → mkcert → test HTTPS
```
## Final Project Structure
```
project-root/
├── backend/ # Django project
├── backend/views.py # Health + CSRF token endpoints
├── certs/ # mkcert SSL certificates
│ ├── localhost+2.pem
│ └── localhost+2-key.pem
├── venv/ # Virtual environment
├── .gitignore
├── db.sqlite3 # Database
├── manage.py
├── requirements.txt # Django, dotenv, DRF, cors-headers, uvicorn
├── run.sh # HTTPS server script (macOS/Linux)
├── run.bat # HTTPS server script (Windows)
└── .vscode/launch.json # Optional VS Code debug config
```
## Version History
- **v3.0.0** - HTTPS-only, mkcert integration, uvicorn server, CORS/CSRF defaults, minimal automation
- **v2.0.0** - Progressive disclosure with bundled content (deprecated)
- **v1.0.0** - Initial monolithic skill (deprecated)
## Security Notes
🔒 **Local development only** - mkcert certificates only work on your machine
🔐 **Never commit** - `certs/`, `*.pem`, `.env` must be in `.gitignore`
⚠️ **Production** - Use real SSL certificates (Let's Encrypt, etc.)

View File

@@ -0,0 +1,404 @@
---
name: django-setup
description: Initialize Django projects for HTTPS development with virtual environments and mkcert SSL certificates
---
## Overview
**This skill sets up Django for HTTPS development** with virtual environments and local SSL certificates.
# Artifacts Builder
To set up Django for HTTPS development with virtual environments and local SSL certificates, follow these steps:
1. Verify/Install Python
2. Create Virtual Environment
3. Install Django and Dependencies
4. Create Django Project
5. Set Up HTTPS
6. Configure settings.py
7. Create a health API
8. Add import and URL routes to urls.py
9. Apply Initial Migrations
10. Test HTTPS Server
11. Create .gitignore
## Step 1: Verify/Install Python
### Check for Python 3.8 - 3.13
**Check all available Python versions:**
Detect the operating system by running `uname -s 2>/dev/null || echo %OS% 2>/dev/null || ver`
Execute the platform-specific command based on the detected system.
```bash
# macOS/Linux
for v in 3.8 3.9 3.10 3.11 3.12 3.13; do
if command -v python$v >/dev/null 2>&1; then
echo "✅ Python $v found: $(python$v --version)"
else
echo "❌ Python $v not found"
fi
done
```
```bash
# Windows
$versions = 3.8, 3.9, 3.10, 3.11, 3.12, 3.13
foreach ($v in $versions) {
try {
$output = py -$v --version 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host "✅ Python $v found: $output"
} else {
Write-Host "❌ Python $v not found"
}
} catch {
Write-Host "❌ Python $v not found"
}
}
```
**Strategy:**
- If you have **any** Python 3.8 - 3.13, use the **highest version**
- If no compatible Python found, install **Python 3.13**
### Install Python 3.13 (if needed)
**No compatible Python?** See platform-specific installation:
- macOS → [platform-install/macos.md](platform-install/macos.md)
- Ubuntu/Debian → [platform-install/linux-ubuntu.md](platform-install/linux-ubuntu.md)
- Fedora/RHEL → [platform-install/linux-fedora.md](platform-install/linux-fedora.md)
- Windows → [platform-install/windows.md](platform-install/windows.md)
**Verify installation:**
```bash
python3.13 --version # or python3.12, python3.11, etc.
which python3.13 # macOS/Linux
where python # Windows
```
---
## Step 2: Create Virtual Environment
**Create venv with your Python version:**
```bash
# Use highest available version
python3.13 -m venv venv # macOS/Linux
py -3.13 -m venv venv # Windows
# Or use default python3
python3 -m venv venv
```
**Verify creation:**
```bash
ls venv/bin/activate # macOS/Linux - should exist
dir venv\Scripts\activate # Windows - should exist
```
**Errors?** See [troubleshooting/venv-issues.md](troubleshooting/venv-issues.md)
---
## Step 3: Install Django and Dependencies
**Activate virtual environment and upgrade pip:**
```bash
# macOS/Linux
source venv/bin/activate
pip install --upgrade pip
# Windows (PowerShell)
venv\Scripts\Activate.ps1
pip install --upgrade pip
# Windows (CMD)
venv\Scripts\activate.bat
pip install --upgrade pip
```
**Install core dependencies:**
```bash
pip install Django python-dotenv djangorestframework
```
**What's installed:**
- **Django** - Web framework
- **python-dotenv** - Environment variable management (for secrets)
- **djangorestframework** - REST API toolkit (optional but recommended)
**Update requirements.txt:**
```bash
pip freeze > requirements.txt
```
**Installation issues?** See [troubleshooting/pip-problems.md](troubleshooting/pip-problems.md)
---
## Step 4: Create Django Project
**Create project in current directory (flat structure):**
```bash
django-admin startproject backend .
```
**Important:** The `.` creates the project in your current directory, not a subdirectory.
**Verify creation:**
```bash
ls manage.py # Should exist
ls backend/settings.py # Should exist
```
---
## Step 5: Set Up HTTPS with mkcert
### Detect Operating System
Detect the operating system if you have not done it yet by running:
```bash
uname -s 2>/dev/null || echo %OS% 2>/dev/null || ver
```
### Platform-Specific Instructions
Follow the instructions for your operating system:
- **macOS** → [platform-https/mkcert-https-setup-macos.md](platform-https/mkcert-https-setup-macos.md)
- **Ubuntu/Debian (Linux)** → [platform-https/mkcert-https-setup-linux.md](platform-https/mkcert-https-setup-linux.md)
- **Windows** → [platform-https/mkcert-https-setup-windows.md](platform-https/mkcert-https-setup-windows.md)
**What these guides cover:**
1. Installing mkcert
2. Installing local certificate authority
3. Creating SSL certificates directory
4. Installing Uvicorn (ASGI server with SSL support)
5. Updating requirements.txt
6. Creating platform-specific run script (run.sh or run.bat)
**Note:** Replace `backend` with your project name if different in the run scripts.
### Create VS Code launch configuration:**
For debugging in VS Code, create `.vscode/launch.json`:
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Django HTTPS (Uvicorn)",
"type": "debugpy",
"request": "launch",
"module": "uvicorn",
"args": [
"backend.asgi:application",
"--host", "0.0.0.0",
"--port", "8000",
"--ssl-keyfile", "./certs/localhost+2-key.pem",
"--ssl-certfile", "./certs/localhost+2.pem",
"--reload"
],
"django": true,
"justMyCode": true,
"python": "${workspaceFolder}/venv/bin/python"
}
]
}
```
---
## Step 6: Configure `settings.py`
### Find the settings file using Glob tool with pattern "**/*settings.py"
**Editing steps for `settings.py`:**
- Add FRONTEND_URL, ALLOWED_HOSTS, CORS_ALLOWED_ORIGINS AND CSRF_TRUSTED_ORIGINS
- Update INSTALLED_APPS
- Update MIDDLEWARE
### Add FRONTEND_URL, ALLOWED_HOSTS, CORS_ALLOWED_ORIGINS AND CSRF_TRUSTED_ORIGINS
Find the line `ALLOWED_HOSTS = []` in settings.py and replace that single line with:
```python
FRONTEND_URL = 'https://localhost:5173'
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
FRONTEND_URL,
]
CSRF_TRUSTED_ORIGINS = [
FRONTEND_URL,
]
```
### Update INSTALLED_APPS
Find the `INSTALLED_APPS` list and append the following to the end of the list:
```python
# Cross-Origin Resource Sharing
'corsheaders',
# REST API support
'rest_framework',
```
### Update MIDDLEWARE
Find the `MIDDLEWARE` list. After `'django.contrib.sessions.middleware.SessionMiddleware',`, add:
```python
'corsheaders.middleware.CorsMiddleware',
```
**Critical:**
- `CorsMiddleware` must come AFTER `SessionMiddleware` and BEFORE `CommonMiddleware`
**Expected result:**
```python
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', # ← Add here
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
```
---
## Step 7: Create a health API
### Create backend/views.py (next to settings.py/urls.py):
```python
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.middleware.csrf import get_token
def api_health(request):
return JsonResponse({
"status": "ok",
"message": "Django is alive and speaking HTTPS",
})
@csrf_exempt
def csrf_token_view(request):
# This forces Django to generate/set the csrftoken cookie
token = get_token(request)
return JsonResponse({"csrftoken": token})
```
---
## Step 8: Add import and URL routes to `urls.py`
first add `from .views import api_health, csrf_token_view` to imports and then add these endpoints to `urls.py`:
```python
path('api/health/', api_health),
path('api/csrf/', csrf_token_view),
```
---
## Step 9: Apply Initial Migrations
**Run database migrations:**
```bash
python manage.py migrate
```
**Creates:**
- `db.sqlite3` database file
- Default tables for auth, admin, sessions
---
## Step 10: Test HTTPS Server
**Start the HTTPS server:**
**macOS/Linux:**
```bash
./run.sh
```
**Windows:**
```bat
run.bat
```
**Expected output:**
```
INFO: Started server process [12345]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on https://127.0.0.1:8000 (Press CTRL+C to quit)
```
**Open browser and visit:**
```
https://localhost:8000
```
**Expected:**
- ✅ Django welcome page (rocket ship)
- ✅ **No certificate warnings** (padlock icon shows secure)
- ✅ URL shows `https://` not `http://`
**If you see certificate warnings:** mkcert CA not properly installed. Run `mkcert -install` again and restart browser.
**Stop server:** Press `Ctrl+C`
**Issues?** See [mkcert-https-setup troubleshooting](../mkcert-https-setup/SKILL.md#common-issues--solutions)
---
## Step 11: Create .gitignore
**Strategy: Check for existing .gitignore first, then create or enhance accordingly.**
### Check if .gitignore already exists
**First, check if .gitignore exists in the project root:**
```bash
ls -la <path-to-root>/.gitignore
```
### Option A: No .gitignore exists
**If .gitignore does not exist, create it using the script at `scripts/create_gitignore.py`:**
```bash
# Create .gitignore in project root
python <path-to-this-skill>/django-setup/scripts/create_gitignore.py --output .
```
**Verify creation at project root:**
```bash
ls -la <path-to-root>/.gitignore # Should exist at project root
cat <path-to-root>/.gitignore # Review contents
```
### Option B: .gitignore already exists
**If .gitignore already exists, enhance it manually by reading both files and merging missing entries:**
1. **Read the existing .gitignore** to understand what's already covered
2. **Read the template** at `.claude/skills/django-setup/examples/.gitignore-template`
3. **Compare both files** to identify missing entries from the template
4. **Use the Edit tool** to append missing sections/entries to the existing .gitignore, preserving the existing content
5. **Avoid duplicates** - only add entries that don't already exist (case-insensitive comparison)
---

View File

@@ -0,0 +1,99 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Virtual Environment
venv/
env/
ENV/
.venv
# Django
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
/media
/staticfiles
# Environment Variables
.env
.env.local
.env.development
.env.production
.env.staging
*.env
# IDE / Editor
.vscode/
.idea/
*.swp
*.swo
*~
.project
.pydevproject
.settings/
# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
Desktop.ini
# SSL Certificates (if using mkcert)
certs/
*.pem
*.key
*.crt
*.cert
# Testing
.coverage
.coverage.*
htmlcov/
.tox/
.pytest_cache/
nosetests.xml
coverage.xml
*.cover
# Jupyter Notebook
.ipynb_checkpoints
# Documentation builds
docs/_build/
site/
# PyCharm
.idea/
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/

View File

@@ -0,0 +1,91 @@
## Step 5: Set Up HTTPS with mkcert (Ubuntu/Debian)
**1. Install mkcert (if not already installed):**
```bash
sudo apt install libnss3-tools
curl -JLO "https://dl.filippo.io/mkcert/latest?for=linux/amd64"
chmod +x mkcert-v*-linux-amd64
sudo mv mkcert-v*-linux-amd64 /usr/local/bin/mkcert
```
**2. Install local certificate authority:**
```bash
mkcert -install
```
**3. Create certificates directory:**
```bash
mkdir certs
mkcert -cert-file certs/localhost+2.pem -key-file certs/localhost+2-key.pem localhost 127.0.0.1 ::1
```
This creates:
• certs/localhost+2.pem (certificate)
• certs/localhost+2-key.pem (private key)
**4. Install Uvicorn (ASGI server with SSL support):**
Ensure you are at the project root and venv is activated:
```bash
pip install uvicorn[standard]
```
**5. Update requirements.txt:**
```bash
pip freeze > requirements.txt
```
**6. Create run.sh script (Linux):**
```bash
cat > run.sh << 'EOF'
#!/usr/bin/env bash
uvicorn backend.asgi:application \
--host 127.0.0.1 --port 8000 \
--ssl-keyfile ./certs/localhost+2-key.pem \
--ssl-certfile ./certs/localhost+2.pem
EOF
chmod +x run.sh
```
Note: Replace backend with your project name if different.
**7. Create VS Code launch configuration (optional):**
For debugging in VS Code, create `.vscode/launch.json`:
```bash
mkdir -p .vscode
cat > .vscode/launch.json << 'EOF'
{
"version": "0.2.0",
"configurations": [
{
"name": "Django HTTPS (Uvicorn)",
"type": "debugpy",
"request": "launch",
"module": "uvicorn",
"args": [
"backend.asgi:application",
"--host", "0.0.0.0",
"--port", "8000",
"--ssl-keyfile", "./certs/localhost+2-key.pem",
"--ssl-certfile", "./certs/localhost+2.pem",
"--reload"
],
"django": true,
"justMyCode": true,
"python": "${workspaceFolder}/venv/bin/python"
}
]
}
EOF
```
This allows you to:
- Run and debug Django with F5 in VS Code
- Set breakpoints in your Django code
- Automatic venv activation via the `python` path
Note: Replace `backend` with your project name if different.

View File

@@ -0,0 +1,50 @@
## Step 5: Set Up HTTPS with mkcert (macOS)
**1. Install mkcert (if not already installed):**
```bash
brew install mkcert
```
**2. Install local certificate authority:**
```bash
mkcert -install
```
**3. Create certificates directory:**
```bash
mkdir certs
mkcert -cert-file certs/localhost+2.pem -key-file certs/localhost+2-key.pem localhost 127.0.0.1 ::1
```
This creates:
• certs/localhost+2.pem (certificate)
• certs/localhost+2-key.pem (private key)
**4. Install Uvicorn (ASGI server with SSL support):**
Ensure you are at the project root and venv is activated:
```bash
pip install 'uvicorn[standard]'
```
**5. Update requirements.txt:**
```bash
pip freeze > requirements.txt
```
**6. Create run.sh script (macOS/Linux):**
```bash
cat > run.sh << 'EOF'
#!/usr/bin/env bash
uvicorn backend.asgi:application \
--host 127.0.0.1 --port 8000 \
--ssl-keyfile ./certs/localhost+2-key.pem \
--ssl-certfile ./certs/localhost+2.pem
EOF
chmod +x run.sh
```
Note: Replace backend with your project name if different.

View File

@@ -0,0 +1,83 @@
## Step 5: Set Up HTTPS with mkcert (Windows)
**1. Install mkcert (if not already installed):**
```powershell
choco install mkcert
```
**2. Install local certificate authority:**
```powershell
mkcert -install
```
**3. Create certificates directory:**
```powershell
mkdir certs
mkcert -cert-file certs/localhost+2.pem -key-file certs/localhost+2-key.pem localhost 127.0.0.1 ::1
```
This creates:
• certs/localhost+2.pem (certificate)
• certs/localhost+2-key.pem (private key)
**4. Install Uvicorn (ASGI server with SSL support):**
Ensure you are at the project root and venv is activated:
```powershell
pip install uvicorn[standard]
```
**5. Update requirements.txt:**
```powershell
pip freeze > requirements.txt
```
**6. Create run.bat script (Windows):**
```batch
@echo off
uvicorn backend.asgi:application ^
--host 127.0.0.1 --port 8000 ^
--ssl-keyfile ./certs/localhost+2-key.pem ^
--ssl-certfile ./certs/localhost+2.pem
```
Note: Replace backend with your project name if different.
**7. Create VS Code launch configuration (optional):**
For debugging in VS Code, create `.vscode/launch.json`:
```powershell
mkdir .vscode -Force
@"
{
"version": "0.2.0",
"configurations": [
{
"name": "Django HTTPS (Uvicorn)",
"type": "debugpy",
"request": "launch",
"module": "uvicorn",
"args": [
"backend.asgi:application",
"--host", "0.0.0.0",
"--port", "8000",
"--ssl-keyfile", "./certs/localhost+2-key.pem",
"--ssl-certfile", "./certs/localhost+2.pem",
"--reload"
],
"django": true,
"justMyCode": true,
"python": "`${workspaceFolder}/venv/Scripts/python.exe"
}
]
}
"@ | Out-File -FilePath .vscode/launch.json -Encoding utf8
```
This allows you to:
- Run and debug Django with F5 in VS Code
- Set breakpoints in your Django code
- Automatic venv activation via the `python` path
Note: Replace `backend` with your project name if different. On Windows, the Python path uses `venv/Scripts/python.exe`.

View File

@@ -0,0 +1,200 @@
# Python Installation - Fedora/RHEL/CentOS
## Check Current Version
```bash
python3 --version
```
If you see Python 3.11+, you're good to go! [← Back to main skill](../SKILL.md#step-2-create-virtual-environment)
---
## Installation Methods
### Option 1: DNF Package Manager (Fedora)
**Fedora usually includes recent Python versions:**
```bash
sudo dnf install python3.11 python3.11-devel python3.11-pip -y
```
**For Python 3.12/3.13 (if available):**
```bash
sudo dnf install python3.13 python3.13-devel -y
```
**Verify:**
```bash
python3.13 --version
```
---
### Option 2: RHEL/CentOS (Using EPEL)
**Enable EPEL repository:**
```bash
sudo dnf install epel-release -y
sudo dnf update -y
```
**Install Python:**
```bash
sudo dnf install python3.11 python3.11-devel python3.11-pip -y
```
---
### Option 3: Build from Source (Advanced)
**Install build dependencies:**
```bash
sudo dnf groupinstall "Development Tools" -y
sudo dnf install gcc openssl-devel bzip2-devel libffi-devel zlib-devel -y
```
**Download and build Python 3.13:**
```bash
cd /tmp
wget https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz
tar xzf Python-3.13.0.tgz
cd Python-3.13.0
./configure --enable-optimizations
make -j $(nproc)
sudo make altinstall # Don't use 'install', use 'altinstall' to avoid replacing system python
```
**Verify:**
```bash
python3.13 --version
```
---
### Option 4: pyenv (Multiple Versions)
**Install dependencies:**
```bash
sudo dnf install gcc make patch zlib-devel bzip2 bzip2-devel \
readline-devel sqlite sqlite-devel openssl-devel tk-devel \
libffi-devel xz-devel -y
```
**Install pyenv:**
```bash
curl https://pyenv.run | bash
```
**Add to ~/.bashrc:**
```bash
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
```
**Reload shell:**
```bash
source ~/.bashrc
```
**Install Python 3.13:**
```bash
pyenv install 3.13.0
pyenv global 3.13.0
```
**Verify:**
```bash
python --version
```
---
## Set Default Python Version
**Check available versions:**
```bash
ls /usr/bin/python*
```
**Set alternative:**
```bash
sudo alternatives --install /usr/bin/python3 python3 /usr/bin/python3.13 1
sudo alternatives --config python3
```
---
## Install pip
**Usually installed with python3:**
```bash
python3 -m pip --version
```
**If missing:**
```bash
sudo dnf install python3-pip -y
```
**Upgrade pip:**
```bash
python3 -m pip install --user --upgrade pip
```
---
## Troubleshooting
### Issue: `No package python3.13 available`
**Solutions:**
1. Check Fedora version: `cat /etc/fedora-release`
2. Update system: `sudo dnf update -y`
3. Try older version: `sudo dnf install python3.11 -y`
4. Use pyenv (Option 4 above)
### Issue: `No module named 'venv'`
**Install venv (usually included):**
```bash
sudo dnf install python3.13-venv -y
```
### Issue: Development headers missing
**Install development package:**
```bash
sudo dnf install python3.13-devel -y
```
### Issue: Permission denied
**Don't use sudo with pip inside venv:**
```bash
python3 -m venv venv
source venv/bin/activate
pip install <package> # No sudo needed
```
---
## Verification Checklist
- [ ] `python3 --version` shows 3.11+
- [ ] `python3 -m venv --help` works
- [ ] `python3 -m pip --version` works
- [ ] Can create test venv: `python3 -m venv test_venv`
- [ ] Can activate: `source test_venv/bin/activate`
**Clean up test:**
```bash
rm -rf test_venv
```
---
[← Back to django-project-setup](../SKILL.md)

View File

@@ -0,0 +1,190 @@
# Python Installation - Ubuntu/Debian
## Check Current Version
```bash
python3 --version
```
If you see Python 3.11+, you're good to go! [← Back to main skill](../SKILL.md#step-2-create-virtual-environment)
---
## Installation Methods
### Option 1: From Ubuntu PPA (Recommended for Latest Versions)
**For Python 3.13 (latest):**
```bash
sudo apt update
sudo apt install software-properties-common -y
sudo add-apt-repository ppa:deadsnakes/ppa -y
sudo apt update
sudo apt install python3.13 python3.13-venv python3.13-dev -y
```
**For Python 3.11:**
```bash
sudo apt update
sudo apt install software-properties-common -y
sudo add-apt-repository ppa:deadsnakes/ppa -y
sudo apt update
sudo apt install python3.11 python3.11-venv python3.11-dev -y
```
**Verify installation:**
```bash
python3.13 --version
```
---
### Option 2: System Package Manager (Older Versions)
**Ubuntu 22.04+ includes Python 3.10+ by default:**
```bash
sudo apt update
sudo apt install python3 python3-venv python3-pip python3-dev -y
```
**Check version:**
```bash
python3 --version
```
---
### Option 3: pyenv (Multiple Versions)
**Install dependencies:**
```bash
sudo apt update
sudo apt install -y make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev \
libffi-dev liblzma-dev
```
**Install pyenv:**
```bash
curl https://pyenv.run | bash
```
**Add to ~/.bashrc or ~/.zshrc:**
```bash
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
```
**Reload shell:**
```bash
source ~/.bashrc # or source ~/.zshrc
```
**Install Python 3.13:**
```bash
pyenv install 3.13.0
pyenv global 3.13.0
```
**Verify:**
```bash
python --version
```
---
## Set Default Python Version
**If you installed Python 3.13 but `python3` still points to old version:**
```bash
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.13 1
sudo update-alternatives --config python3
```
**Select the number for Python 3.13**
---
## Install pip
**For Python 3.13:**
```bash
sudo apt install python3.13-distutils -y
curl -sS https://bootstrap.pypa.io/get-pip.py | python3.13
```
**Or use system package:**
```bash
sudo apt install python3-pip -y
```
**Verify:**
```bash
python3 -m pip --version
```
---
## Troubleshooting
### Issue: `E: Unable to locate package python3.13`
**Solution:** Add deadsnakes PPA (see Option 1 above)
### Issue: `No module named 'venv'`
**Install venv module:**
```bash
sudo apt install python3.13-venv -y
```
### Issue: `No module named 'distutils'`
**Install distutils:**
```bash
sudo apt install python3.13-distutils -y
```
### Issue: Build dependencies missing (for pyenv)
**Install build essentials:**
```bash
sudo apt install build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev curl \
libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev -y
```
### Issue: Permission denied when installing packages
**Don't use sudo with pip!** Use virtual environments instead:
```bash
python3 -m venv venv
source venv/bin/activate
pip install <package>
```
---
## Verification Checklist
- [ ] `python3 --version` shows 3.11+
- [ ] `python3 -m venv --help` shows venv usage
- [ ] `python3 -m pip --version` works
- [ ] Can create test venv: `python3 -m venv test_venv`
- [ ] Can activate: `source test_venv/bin/activate`
**Clean up test:**
```bash
rm -rf test_venv
```
---
[← Back to django-project-setup](../SKILL.md)

View File

@@ -0,0 +1,184 @@
# Python Installation - macOS
## Check Current Version
```bash
python3 --version
```
If you see Python 3.11+, you're good to go! [← Back to main skill](../SKILL.md#step-2-create-virtual-environment)
---
## Installation Methods
### Option 1: Homebrew (Recommended)
**Why Homebrew:**
- Easy updates: `brew upgrade python@3.13`
- Manages dependencies automatically
- Industry standard on macOS
**Install Homebrew (if not installed):**
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
**Install Python 3.13:**
```bash
brew install python@3.13
```
**Verify installation:**
```bash
python3.13 --version
# Or if it's the default:
python3 --version
```
**Add to PATH (if needed):**
```bash
echo 'export PATH="/opt/homebrew/bin:$PATH"' >> ~/.zshrc # For M1/M2 Macs
echo 'export PATH="/usr/local/bin:$PATH"' >> ~/.zshrc # For Intel Macs
source ~/.zshrc
```
---
### Option 2: Official Python Installer
**When to use:** You want specific Python version or don't use Homebrew
**Steps:**
1. Visit [python.org/downloads](https://www.python.org/downloads/)
2. Click "Download Python 3.13.x" button
3. Open downloaded `.pkg` file
4. Follow installation wizard
5. Restart Terminal
**Verify:**
```bash
python3 --version
```
**Add to PATH (if needed):**
```bash
echo 'export PATH="/Library/Frameworks/Python.framework/Versions/3.13/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
```
---
### Option 3: pyenv (Multiple Python Versions)
**Why pyenv:**
- Manage multiple Python versions side-by-side
- Easy switching between projects
- Preferred by professional developers
**Install pyenv:**
```bash
brew install pyenv
```
**Install Python 3.13:**
```bash
pyenv install 3.13.0
```
**Set as global default:**
```bash
pyenv global 3.13.0
```
**Or set for specific project:**
```bash
cd /path/to/project
pyenv local 3.13.0
```
**Configure shell (add to ~/.zshrc):**
```bash
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
```
**Reload shell:**
```bash
source ~/.zshrc
```
**Verify:**
```bash
python --version # Should show 3.13.0
```
---
## Troubleshooting
### Issue: `command not found: python3`
**After Homebrew install:**
```bash
brew link python@3.13
```
**Check where Python is:**
```bash
which python3
brew --prefix python@3.13
```
### Issue: Multiple Python versions conflict
**List all Python installations:**
```bash
which -a python3
ls -l /usr/local/bin/python*
```
**Use specific version:**
```bash
python3.13 -m venv venv # Force Python 3.13
```
### Issue: SSL certificate errors
**Install certificates:**
```bash
/Applications/Python\ 3.13/Install\ Certificates.command
```
Or via Homebrew:
```bash
brew install openssl
```
### Issue: Xcode Command Line Tools needed
**Install:**
```bash
xcode-select --install
```
---
## Verification Checklist
- [ ] `python3 --version` shows 3.11+
- [ ] `which python3` shows installation path
- [ ] `python3 -m pip --version` works
- [ ] `python3 -m venv test_venv` creates test environment
- [ ] Can activate test venv: `source test_venv/bin/activate`
**Clean up test:**
```bash
rm -rf test_venv
```
---
[← Back to django-project-setup](../SKILL.md)

View File

@@ -0,0 +1,267 @@
# Python Installation - Windows
## Check Current Version
**PowerShell or Command Prompt:**
```powershell
python --version
```
If you see Python 3.11+, you're good to go! [← Back to main skill](../SKILL.md#step-2-create-virtual-environment)
---
## Installation Methods
### Option 1: Official Python Installer (Recommended)
**Why this method:**
- Official releases from python.org
- Includes pip automatically
- Easy installation
**Steps:**
1. Visit [python.org/downloads](https://www.python.org/downloads/)
2. Click **"Download Python 3.13.x"** button
3. Run the downloaded `.exe` installer
**⚠️ CRITICAL: Check "Add Python to PATH"**
- This checkbox is at the bottom of the installer
- **Must check this box** or Python won't work from command line
4. Click "Install Now"
5. Wait for installation to complete
6. Click "Close"
**Verify installation:**
```powershell
python --version
pip --version
```
---
### Option 2: Microsoft Store (Windows 10/11)
**Why this method:**
- Easiest installation
- Automatic PATH configuration
- Auto-updates through Microsoft Store
**Steps:**
1. Open **Microsoft Store** app
2. Search for "Python 3.13"
3. Click **"Get"** or **"Install"**
4. Wait for installation
5. Restart terminal
**Verify:**
```powershell
python --version
```
---
### Option 3: Chocolatey Package Manager
**Why this method:**
- Command-line package management (like Homebrew on macOS)
- Good for automated setups
- Easy updates: `choco upgrade python`
**Install Chocolatey first:**
Open **PowerShell as Administrator** and run:
```powershell
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
```
**Install Python:**
```powershell
choco install python --version=3.13.0
```
**Verify:**
```powershell
python --version
```
---
### Option 4: Scoop Package Manager
**Why this method:**
- Lightweight package manager
- No admin rights required
- Clean installations
**Install Scoop:**
```powershell
irm get.scoop.sh | iex
```
**Install Python:**
```powershell
scoop install python
```
**Verify:**
```powershell
python --version
```
---
## Configure PATH (If Python Not Found)
### Check if Python is in PATH
**Open Command Prompt and run:**
```cmd
where python
```
**If nothing appears, Python is not in PATH.**
### Add Python to PATH Manually
**Find Python installation location:**
- Official installer: `C:\Users\<YourName>\AppData\Local\Programs\Python\Python313\`
- Microsoft Store: `C:\Users\<YourName>\AppData\Local\Microsoft\WindowsApps\`
**Add to PATH:**
1. Open **Start Menu**
2. Search "Environment Variables"
3. Click **"Edit the system environment variables"**
4. Click **"Environment Variables"** button
5. Under "User variables", select **"Path"**
6. Click **"Edit"**
7. Click **"New"**
8. Add Python paths:
- `C:\Users\<YourName>\AppData\Local\Programs\Python\Python313\`
- `C:\Users\<YourName>\AppData\Local\Programs\Python\Python313\Scripts\`
9. Click **"OK"** on all dialogs
10. **Restart terminal/PowerShell**
**Verify:**
```powershell
python --version
```
---
## Troubleshooting
### Issue: `python: command not found`
**Solution 1: Use `py` launcher instead**
```powershell
py --version
py -m venv venv
```
**Solution 2: Add to PATH** (see section above)
**Solution 3: Reinstall Python**
- Uninstall current Python
- Reinstall and **check "Add Python to PATH"**
### Issue: Multiple Python versions installed
**List all versions:**
```powershell
py --list
```
**Use specific version:**
```powershell
py -3.13 --version
py -3.13 -m venv venv
```
### Issue: PowerShell Execution Policy Error
**When activating venv:**
```
venv\Scripts\Activate.ps1 : File cannot be loaded because running scripts is disabled
```
**Solution:**
```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
**Then retry activation:**
```powershell
venv\Scripts\Activate.ps1
```
### Issue: `pip` not found
**Use python -m pip instead:**
```powershell
python -m pip --version
python -m pip install --upgrade pip
```
### Issue: Long path errors
**Enable long paths in Windows:**
Open **PowerShell as Administrator**:
```powershell
New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name "LongPathsEnabled" -Value 1 -PropertyType DWORD -Force
```
Restart computer.
---
## Using Windows Subsystem for Linux (WSL)
**Alternative: Use Linux Python on Windows**
**Install WSL:**
```powershell
wsl --install
```
**Install Ubuntu:**
```powershell
wsl --install -d Ubuntu
```
**Then follow:** [linux-ubuntu.md](linux-ubuntu.md) for Python installation
---
## Verification Checklist
- [ ] `python --version` shows 3.11+ (or `py --version`)
- [ ] `pip --version` works (or `py -m pip --version`)
- [ ] `python -m venv test_venv` creates test environment
- [ ] Can activate test venv: `test_venv\Scripts\activate`
- [ ] Prompt shows `(test_venv)` prefix
**Clean up test:**
```powershell
rmdir /s test_venv
```
---
## Development Tools (Optional)
**Install Windows Terminal** (better than Command Prompt):
- Download from Microsoft Store
- Or: https://aka.ms/terminal
**Install Git for Windows:**
- Download from: https://git-scm.com/download/win
**Install VS Code:**
- Download from: https://code.visualstudio.com/
---
[← Back to django-project-setup](../SKILL.md)

View File

@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""
Script to create .gitignore file from template.
Usage:
python create_gitignore.py --output /path/to/project
python create_gitignore.py --output .
"""
import argparse
import os
import shutil
from pathlib import Path
def create_gitignore(output_dir: str) -> None:
"""
Copy .gitignore template to the specified output directory.
Args:
output_dir: Directory where .gitignore should be created
"""
# Get the directory where this script is located
script_dir = Path(__file__).parent
skill_dir = script_dir.parent
# Path to the template
template_path = skill_dir / "examples" / ".gitignore-template"
# Validate template exists
if not template_path.exists():
raise FileNotFoundError(
f"Template not found at: {template_path}\n"
f"Expected location: .claude/skills/django-setup/examples/.gitignore-template"
)
# Create output directory if it doesn't exist
output_path = Path(output_dir).resolve()
output_path.mkdir(parents=True, exist_ok=True)
# Destination path
gitignore_path = output_path / ".gitignore"
# Check if .gitignore already exists
if gitignore_path.exists():
print(f"⚠️ .gitignore already exists at: {gitignore_path}")
print("❌ Script should only be used when .gitignore does not exist.")
print("💡 Use manual merging to add missing entries from the template.")
exit(1)
# Copy the template
shutil.copy2(template_path, gitignore_path)
print(f"✅ Created .gitignore at: {gitignore_path}")
print(f"📋 Copied from template: {template_path}")
def main():
parser = argparse.ArgumentParser(
description="Create .gitignore file from template for Django projects",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Create .gitignore in current directory
python create_gitignore.py --output .
# Create .gitignore in specific project directory
python create_gitignore.py --output /path/to/project
# Create .gitignore in parent directory
python create_gitignore.py --output ..
"""
)
parser.add_argument(
'--output',
type=str,
required=True,
help='Directory where .gitignore should be created (e.g., . for current directory)'
)
args = parser.parse_args()
try:
create_gitignore(args.output)
except FileNotFoundError as e:
print(f"❌ Error: {e}")
exit(1)
except Exception as e:
print(f"❌ Unexpected error: {e}")
exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,480 @@
# Troubleshooting: Django Errors
[← Back to main skill](../SKILL.md)
---
## Issue: `django-admin: command not found` {#django-admin}
**After installing Django, command doesn't work**
### Solutions:
**Ensure venv is activated:**
```bash
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # Windows
```
**Use `python -m django` instead:**
```bash
python -m django --version
python -m django startproject myproject
```
**Check Django is installed:**
```bash
pip list | grep Django
# or
pip show Django
```
**Reinstall Django:**
```bash
pip install --force-reinstall Django
```
---
## Issue: Port 8000 Already in Use {#port-in-use}
**Error:**
```
Error: That port is already in use.
```
### Solutions:
**Use different port:**
```bash
python manage.py runserver 8001
python manage.py runserver 0.0.0.0:8080
```
**Kill process using port 8000:**
**macOS/Linux:**
```bash
lsof -ti:8000 | xargs kill -9
```
**Windows (PowerShell):**
```powershell
netstat -ano | findstr :8000
# Note the PID, then:
taskkill /PID <pid> /F
```
**Windows (Command Prompt):**
```cmd
FOR /F "tokens=5" %P IN ('netstat -ano ^| findstr :8000') DO TaskKill /PID %P /F
```
---
## Issue: `ModuleNotFoundError: No module named 'django'`
**Django installed but Python can't find it**
### Solutions:
**Verify venv is activated:**
```bash
which python # Should point to venv/bin/python
echo $VIRTUAL_ENV # Should show venv path
```
**Check Django installation:**
```bash
pip list
pip show Django
```
**Install Django in venv:**
```bash
source venv/bin/activate
pip install Django
```
**Check you're using venv Python:**
```bash
python --version
which python
```
---
## Issue: `django.core.exceptions.ImproperlyConfigured`
**Common misconfigurations**
### `SECRET_KEY` not set
**Error:**
```
ImproperlyConfigured: The SECRET_KEY setting must not be empty.
```
**Solution:**
- Don't delete SECRET_KEY from settings.py
- If using environment variables, ensure .env file exists
### Database configuration error
**Error:**
```
ImproperlyConfigured: settings.DATABASES is improperly configured
```
**Solution - Check database settings:**
```python
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
```
---
## Issue: Migrations Not Applying
**Error:**
```
django.db.utils.OperationalError: no such table
```
### Solutions:
**Run migrations:**
```bash
python manage.py migrate
```
**Check migration files exist:**
```bash
ls */migrations/
# Should see 0001_initial.py files
```
**Reset database (development only!):**
```bash
rm db.sqlite3
python manage.py migrate
```
**Make migrations if they don't exist:**
```bash
python manage.py makemigrations
python manage.py migrate
```
---
## Issue: Static Files Not Loading
**CSS/JS files show 404 in browser**
### Solutions:
**Run collectstatic:**
```bash
python manage.py collectstatic
```
**Check STATIC_URL in settings.py:**
```python
STATIC_URL = '/static/'
```
**For development, ensure DEBUG=True:**
```python
DEBUG = True
```
**Check INSTALLED_APPS includes:**
```python
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
]
```
---
## Issue: Template Not Found
**Error:**
```
TemplateDoesNotExist at /path/
```
### Solutions:
**Check template path:**
```python
# settings.py
TEMPLATES = [
{
'DIRS': [BASE_DIR / 'templates'], # Add this
...
},
]
```
**Create templates directory:**
```bash
mkdir -p templates
```
**Check template name matches:**
```python
# views.py
return render(request, 'index.html') # Must match file name exactly
```
---
## Issue: ALLOWED_HOSTS Error in Production
**Error:**
```
Invalid HTTP_HOST header: 'yourdomain.com'. You may need to add 'yourdomain.com' to ALLOWED_HOSTS.
```
### Solution:
**Add domain to ALLOWED_HOSTS:**
```python
# settings.py
DEBUG = False # In production
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']
```
**For development:**
```python
DEBUG = True
ALLOWED_HOSTS = [] # Empty list allows localhost automatically
```
---
## Issue: CSRF Verification Failed
**Error:**
```
Forbidden (403)
CSRF verification failed. Request aborted.
```
### Solutions:
**Ensure CSRF middleware is enabled:**
```python
# settings.py
MIDDLEWARE = [
...
'django.middleware.csrf.CsrfViewMiddleware',
...
]
```
**Include CSRF token in forms:**
```html
<form method="post">
{% csrf_token %}
...
</form>
```
**For AJAX, include CSRF token in headers:**
```javascript
// Get CSRF token from cookie
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
fetch('/api/endpoint/', {
method: 'POST',
headers: {
'X-CSRFToken': csrftoken
}
})
```
---
## Issue: Admin Interface Not Working
**Can't access /admin/**
### Solutions:
**Run migrations:**
```bash
python manage.py migrate
```
**Create superuser:**
```bash
python manage.py createsuperuser
```
**Check URL configuration:**
```python
# urls.py
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
]
```
**Ensure admin app is installed:**
```python
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
]
```
---
## Issue: Project Won't Start After Renaming
**Renamed project but errors occur**
### Solution:
**Update references in these files:**
**manage.py:**
```python
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_name.settings')
```
**asgi.py:**
```python
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_name.settings')
```
**wsgi.py:**
```python
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_name.settings')
```
**Rename project directory itself**
---
## Issue: Circular Import Errors
**Error:**
```
ImportError: cannot import name 'X' from partially initialized module 'Y'
```
### Solutions:
**Avoid circular imports:**
```python
# ❌ Bad - circular import
# models.py
from .views import something
# views.py
from .models import Model
```
**Use lazy imports:**
```python
# ✅ Good - import inside function
def my_view(request):
from .models import Model # Import here
...
```
**Or use Django's get_model:**
```python
from django.apps import apps
Model = apps.get_model('app_name', 'ModelName')
```
---
## Issue: `SyntaxError` in settings.py
**Error:**
```
SyntaxError: invalid syntax
```
### Solutions:
**Check Python version:**
```bash
python --version # Should be 3.8+
```
**Look for common syntax errors:**
```python
# ❌ Missing comma
INSTALLED_APPS = [
'django.contrib.admin' # Missing comma!
'django.contrib.auth',
]
# ✅ Correct
INSTALLED_APPS = [
'django.contrib.admin', # Comma here
'django.contrib.auth',
]
```
**Validate Python syntax:**
```bash
python -m py_compile backend/settings.py
```
---
## Quick Diagnostic Commands
**Check Django installation:**
```bash
python -m django --version
```
**Check Python version:**
```bash
python --version
```
**Run system checks:**
```bash
python manage.py check
python manage.py check --deploy
```
**List installed packages:**
```bash
pip list
```
**Check migrations status:**
```bash
python manage.py showmigrations
```
**Test database connection:**
```bash
python manage.py dbshell
```
---
[← Back to django-project-setup](../SKILL.md)

View File

@@ -0,0 +1,386 @@
# Troubleshooting: pip Problems
[← Back to main skill](../SKILL.md)
---
## Issue: `pip: command not found` {#pip-not-found}
**After activating venv, pip doesn't work**
### Solutions:
**Use `python -m pip` instead:**
```bash
python -m pip --version
python -m pip install Django
python -m pip install --upgrade pip
```
**Ensure venv is activated:**
```bash
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # Windows
```
**Reinstall pip in venv:**
```bash
python -m ensurepip --upgrade
```
---
## Issue: `pip install` Requires sudo
**Error:**
```
ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied
```
### Solution:
**❌ NEVER use sudo with pip!**
**✅ Use virtual environment instead:**
```bash
# Create and activate venv first
python3 -m venv venv
source venv/bin/activate
# Now install without sudo
pip install Django
```
**Why no sudo:**
- Pollutes system Python
- Breaks system tools
- Security risk
- Conflicts with package manager
---
## Issue: SSL Certificate Errors
**Error:**
```
SSL: CERTIFICATE_VERIFY_FAILED
```
### Solutions:
**macOS - Install certificates:**
```bash
/Applications/Python\ 3.13/Install\ Certificates.command
```
**Or install certifi:**
```bash
pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org certifi
```
**Ubuntu/Debian:**
```bash
sudo apt install ca-certificates
sudo update-ca-certificates
```
**Temporary workaround (not recommended):**
```bash
pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org Django
```
---
## Issue: pip is Outdated
**Warning:**
```
WARNING: You are using pip version X.X.X; however, version Y.Y.Y is available.
```
### Solution:
**Upgrade pip:**
```bash
python -m pip install --upgrade pip
```
**If that fails:**
```bash
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
rm get-pip.py
```
---
## Issue: Package Installation Fails
**Error:**
```
ERROR: Could not find a version that satisfies the requirement <package>
```
### Solutions:
**Check package name spelling:**
```bash
# Wrong
pip install django-rest-framework
# Correct
pip install djangorestframework
```
**Check Python version compatibility:**
```bash
python --version # Some packages require Python 3.11+
```
**Try older package version:**
```bash
pip install "Django<5.0" # Install Django 4.x
```
**Update pip and setuptools:**
```bash
pip install --upgrade pip setuptools wheel
```
---
## Issue: Conflicting Dependencies
**Error:**
```
ERROR: package-a 1.0 has requirement package-b>=2.0, but you'll have package-b 1.5
```
### Solutions:
**Let pip resolve (pip 20.3+):**
```bash
pip install --upgrade <package>
```
**Install specific compatible versions:**
```bash
pip install package-a package-b==2.0
```
**Use pip-tools for dependency management:**
```bash
pip install pip-tools
# Create requirements.in with your deps
pip-compile requirements.in
pip-sync requirements.txt
```
**Nuclear option - recreate venv:**
```bash
deactivate
rm -rf venv
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```
---
## Issue: Building Wheels Failed
**Error:**
```
Failed building wheel for <package>
```
### Solutions:
**Install build dependencies:**
**macOS:**
```bash
xcode-select --install
brew install openssl
```
**Ubuntu/Debian:**
```bash
sudo apt install python3-dev build-essential libssl-dev libffi-dev -y
```
**Fedora/RHEL:**
```bash
sudo dnf install python3-devel gcc openssl-devel libffi-devel -y
```
**Windows:**
- Install Microsoft C++ Build Tools
- Download from: https://visualstudio.microsoft.com/visual-cpp-build-tools/
**Use pre-built wheels:**
```bash
pip install --only-binary :all: <package>
```
---
## Issue: `externally-managed-environment` Error
**Error (Python 3.11+ on some Linux distros):**
```
error: externally-managed-environment
This environment is externally managed
```
### Solution:
**✅ Use virtual environment (recommended):**
```bash
python3 -m venv venv
source venv/bin/activate
pip install Django
```
**Or use `--break-system-packages` (not recommended):**
```bash
pip install --break-system-packages Django # ⚠️ Use at own risk
```
---
## Issue: Slow Download Speed
**Pip takes forever to download packages**
### Solutions:
**Use faster mirror (if in China):**
```bash
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple Django
```
**Increase timeout:**
```bash
pip install --timeout=1000 Django
```
**Use pip cache:**
```bash
pip install Django # First time (slow)
pip install Django # Second time (fast, uses cache)
```
---
## Issue: Hash Mismatch Error
**Error:**
```
THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE
```
### Solutions:
**Regenerate requirements.txt:**
```bash
pip freeze > requirements.txt
```
**Install without hash checking (temporary):**
```bash
pip install --no-deps -r requirements.txt
```
**Clear pip cache:**
```bash
pip cache purge
```
---
## Issue: ImportError After Installing Package
**Package installs but can't import**
### Solutions:
**Verify venv is activated:**
```bash
which python # Should point to venv
pip list # Should show installed package
```
**Check package name vs import name:**
```bash
# Install name: django-cors-headers
pip install django-cors-headers
# Import name: corsheaders
import corsheaders # ← Different!
```
**Restart Python shell:**
```bash
exit() # Exit Python shell
python # Start fresh
import django # Try again
```
---
## Issue: Multiple pip Versions
**`pip` points to wrong Python version**
### Solution:
**Always use `python -m pip`:**
```bash
# Instead of:
pip install Django
# Use:
python -m pip install Django
```
**Or specify Python version:**
```bash
python3.13 -m pip install Django
```
---
## Best Practices
**Always use virtual environments**
```bash
python3 -m venv venv
source venv/bin/activate
```
**Keep pip updated**
```bash
pip install --upgrade pip
```
**Pin versions in production**
```bash
# requirements.txt
Django==5.0.1
djangorestframework==3.14.0
```
**Use requirements.txt**
```bash
pip freeze > requirements.txt
pip install -r requirements.txt
```
**Don't mix conda and pip** (if using Anaconda)
- Use conda for conda packages
- Use pip only for packages not in conda
---
[← Back to django-project-setup](../SKILL.md)

View File

@@ -0,0 +1,376 @@
# Troubleshooting: Virtual Environment Issues
[← Back to main skill](../SKILL.md)
---
## Issue: `ensurepip is not available` {#ensurepip}
**Full error:**
```
Error: Command '[...]/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1
```
### Solutions:
**Ubuntu/Debian:**
```bash
sudo apt install python3.13-venv python3.13-distutils -y
```
**macOS (Homebrew):**
```bash
brew reinstall python@3.13
```
**Windows:**
- Reinstall Python with "pip" option checked
- Or download get-pip.py: https://bootstrap.pypa.io/get-pip.py
---
## Issue: PowerShell Execution Policy {#powershell-execution-policy}
**Error:**
```
venv\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system
```
### Solution:
**Allow scripts for current user:**
```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
**Then retry activation:**
```powershell
venv\Scripts\Activate.ps1
```
**Verify policy:**
```powershell
Get-ExecutionPolicy -List
```
---
## Issue: Virtual Environment Not Activating
**Symptoms:**
- No `(venv)` prefix in prompt
- `which python` still points to system Python
### Solutions:
**macOS/Linux - Check activation command:**
```bash
source venv/bin/activate # Correct
. venv/bin/activate # Also works
bash venv/bin/activate # Wrong - don't use bash
```
**Windows - Use correct script:**
```powershell
# PowerShell
venv\Scripts\Activate.ps1
# Command Prompt
venv\Scripts\activate.bat
# Git Bash
source venv/Scripts/activate
```
**Verify activation:**
```bash
which python # Should point to venv/bin/python
echo $VIRTUAL_ENV # Should show venv path
```
---
## Issue: Permission Denied on Activation {#permission-denied}
**Error (macOS/Linux):**
```
bash: venv/bin/activate: Permission denied
```
### Solution:
**Make script executable:**
```bash
chmod +x venv/bin/activate
source venv/bin/activate
```
**Or recreate venv:**
```bash
rm -rf venv
python3 -m venv venv
```
---
## Issue: `venv` Module Not Found
**Error:**
```
No module named venv
```
### Solutions:
**Ubuntu/Debian:**
```bash
sudo apt install python3.13-venv -y
```
**Fedora/RHEL:**
```bash
sudo dnf install python3.13-venv -y
```
**macOS:**
```bash
# Reinstall Python via Homebrew
brew reinstall python@3.13
# Or install from python.org
```
**Windows:**
- Usually included by default
- Reinstall Python if missing
---
## Issue: Wrong Python Version in venv
**Symptom:**
```bash
(venv) $ python --version
Python 3.8.10 # But you wanted 3.13!
```
### Solution:
**Delete and recreate with specific version:**
```bash
deactivate # If currently activated
rm -rf venv
# Specify exact Python version
python3.13 -m venv venv # macOS/Linux
py -3.13 -m venv venv # Windows
```
**Verify before activating:**
```bash
venv/bin/python --version # Check version first
source venv/bin/activate # Then activate
```
---
## Issue: Can't Deactivate venv
**Symptom:**
- `deactivate` command doesn't work
- Still see `(venv)` in prompt
### Solutions:
**Try deactivate function:**
```bash
deactivate
```
**If that fails, just close terminal:**
- Exit terminal/shell
- Open new terminal
- venv won't be active in new session
**Or manually unset variables:**
```bash
unset VIRTUAL_ENV
export PATH="$OLD_PATH"
```
---
## Issue: venv Created in Wrong Location
**Symptom:**
- venv created in home directory instead of project
- venv in system location
### Solution:
**Delete misplaced venv:**
```bash
rm -rf ~/venv # Or wherever it was created
```
**Navigate to project first:**
```bash
cd /path/to/your/project
pwd # Verify you're in correct directory
python3 -m venv venv # Now create here
```
---
## Issue: `pip` Not Found After Activation
**Error:**
```
(venv) $ pip --version
pip: command not found
```
### Solutions:
**Use `python -m pip` instead:**
```bash
python -m pip --version
python -m pip install <package>
```
**Reinstall pip in venv:**
```bash
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
rm get-pip.py
```
**Or recreate venv:**
```bash
deactivate
rm -rf venv
python3 -m venv venv --clear
```
---
## Issue: venv Taking Too Much Space
**Symptom:**
- venv folder is several GB
- Too many cached packages
### Solutions:
**Clear pip cache:**
```bash
pip cache purge
```
**Remove unnecessary packages:**
```bash
pip list # See what's installed
pip uninstall <package>
```
**Use `--no-cache-dir` when installing:**
```bash
pip install --no-cache-dir Django
```
**Typical venv sizes:**
- Minimal Django: ~100-200 MB
- Full-featured project: ~500 MB - 1 GB
- If >2 GB, something is wrong
---
## Issue: Can't Delete venv Folder
**Windows error:**
```
Access denied
File in use
```
### Solutions:
**Deactivate first:**
```bash
deactivate
```
**Close all terminals/IDEs using that folder**
**Windows - use PowerShell as Admin:**
```powershell
Remove-Item -Recurse -Force venv
```
**Or use File Explorer:**
- Right-click venv folder
- Properties → Security → Advanced
- Take ownership
- Delete
---
## Issue: IDE Not Recognizing venv
**VS Code, PyCharm not using venv Python**
### Solutions:
**VS Code:**
1. Press `Ctrl+Shift+P` (or `Cmd+Shift+P` on Mac)
2. Type "Python: Select Interpreter"
3. Choose `./venv/bin/python`
**PyCharm:**
1. File → Settings (or Preferences on Mac)
2. Project → Python Interpreter
3. Click gear icon → Add
4. Select "Existing environment"
5. Browse to `venv/bin/python`
---
## Best Practices to Avoid Issues
**Always activate before installing packages**
```bash
source venv/bin/activate # Activate first
pip install Django # Then install
```
**One venv per project**
```
project1/
└── venv/
project2/
└── venv/
```
**Don't commit venv to git**
```gitignore
venv/
.venv/
env/
ENV/
```
**Document Python version in README**
```markdown
## Requirements
- Python 3.13+
```
**Use requirements.txt**
```bash
pip freeze > requirements.txt
# Others can: pip install -r requirements.txt
```
---
[← Back to django-project-setup](../SKILL.md)