# 🪟 Windows Development Setup Guide

**Project**: BMC Website Django  
**Environment**: Windows 10/11 Development  
**Database**: SQLite (db.sqlite3)  
**Python**: 3.8, 3.10, or 3.12  
**Last Updated**: April 18, 2026

---

## ✅ Configuration Changes Made

### Database Configuration
✅ **Changed from PostgreSQL to SQLite**
- Old: PostgreSQL (ubuntu/linux production)
- New: SQLite (windows development)
- File: `db.sqlite3`
- Location: Project root directory

### Path Configuration
✅ **All paths use Windows-compatible format**
- Static files: `staticfiles/`
- Media files: `media/`
- Locale: `locale/`

### ALLOWED_HOSTS
✅ **Added localhost for development**
- `localhost`
- `127.0.0.1`
- `127.0.0.1:8000`

---

## 🚀 Quick Start

### 1. Install Python (if not already installed)
```bash
# Download from https://www.python.org/downloads/
# Install Python 3.10+ (recommended)
# ✅ Make sure to check "Add Python to PATH"
```

### 2. Clone/Navigate to Project
```bash
cd "d:\Huy\Project\programing\website-bmc"
```

### 3. Create Virtual Environment
```bash
# Create venv
python -m venv venv

# Activate venv (Windows)
venv\Scripts\activate

# You should see: (venv) C:\...
```

### 4. Install Dependencies
```bash
# Upgrade pip
python -m pip install --upgrade pip

# Install requirements
pip install django==4.0.1
pip install django-ckeditor
pip install pillow
```

### 5. Apply Migrations
```bash
# Create database
python manage.py migrate

# Create superuser (admin account)
python manage.py createsuperuser
# Follow prompts to create admin account
```

### 6. Collect Static Files
```bash
python manage.py collectstatic --noinput
```

### 7. Run Development Server
```bash
python manage.py runserver

# Server will start at: http://127.0.0.1:8000/
```

---

## 🔧 Configuration Details

### Settings.py Changes

#### Database Configuration
**BEFORE (PostgreSQL - Production)**:
```python
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'bmc',
        'USER': 'admin',
        'PASSWORD': '123@456a',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
```

**AFTER (SQLite - Development)**:
```python
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
```

#### Static & Media Files
✅ Now using `os.path.join()` for Windows compatibility:
```python
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale'),
]
```

#### Development Hosts
✅ Added localhost support:
```python
ALLOWED_HOSTS = [
    "bmcgroup.com.vn",
    "www.bmcgroup.com.vn",
    "localhost",          # NEW
    "127.0.0.1",         # NEW
    "127.0.0.1:8000",    # NEW
]
```

---

## 📁 Project Structure

```
website-bmc/
├── manage.py                    # Django CLI
├── db.sqlite3                   # ✅ Database (auto-created)
├── venv/                        # ✅ Virtual environment
│   ├── Scripts/                 # Windows activation scripts
│   │   ├── activate.bat        # Activate venv
│   │   └── python.exe          # Python interpreter
│   └── Lib/                    # Installed packages
├── BMC/                         # ✅ Django config
│   ├── settings.py             # ✅ Updated for Windows
│   ├── urls.py
│   ├── wsgi.py
│   └── asgi.py
├── BmcBase/                     # Main app
│   ├── models.py
│   ├── views.py
│   ├── urls.py
│   └── templates/
├── legal/                       # Legal pages app
│   └── templates/legal/
├── staticfiles/                 # Collected static files
├── media/                       # User uploads
│   ├── products/
│   ├── banners/
│   ├── contacts/
│   └── uploads/
└── locale/                      # i18n translations
```

---

## 🎯 Common Development Tasks

### Start Development Server
```bash
# Activate venv first (if not already)
venv\Scripts\activate

# Start server
python manage.py runserver

# Server runs at: http://127.0.0.1:8000/
# Admin at: http://127.0.0.1:8000/admin/
```

### Create Database
```bash
python manage.py migrate
```

### Make Model Changes
```bash
# Create migration
python manage.py makemigrations

# Apply migration
python manage.py migrate
```

### Create Admin User
```bash
python manage.py createsuperuser
```

### Run Tests
```bash
# All tests
python manage.py test

# Specific app
python manage.py test legal
python manage.py test BmcBase

# With verbose output
python manage.py test --verbosity=2
```

### Collect Static Files
```bash
python manage.py collectstatic --noinput
```

### Clear Database (⚠️ WARNING: Deletes all data!)
```bash
# Remove db.sqlite3 file
del db.sqlite3

# Recreate database
python manage.py migrate

# Create new admin user
python manage.py createsuperuser
```

### Deactivate Virtual Environment
```bash
# Windows
deactivate

# Back to normal command prompt
```

---

## 🔍 Troubleshooting

### Problem: "Python not found" or "python: command not found"
**Solution**:
1. Install Python from https://www.python.org/downloads/
2. Make sure "Add Python to PATH" is checked during installation
3. Restart terminal/PowerShell after installation
4. Verify: `python --version`

### Problem: Virtual environment not activating
**Solution**:
```bash
# Try explicit path
venv\Scripts\activate.bat

# Or in PowerShell
venv\Scripts\Activate.ps1

# If PowerShell execution policy error:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```

### Problem: Port 8000 already in use
**Solution**:
```bash
# Use different port
python manage.py runserver 8001

# Or kill the process using port 8000 (Windows)
netstat -ano | findstr :8000
taskkill /PID <PID> /F
```

### Problem: "No module named 'django'"
**Solution**:
```bash
# Make sure venv is activated
venv\Scripts\activate

# Install Django
pip install django==4.0.1
```

### Problem: Static files not loading
**Solution**:
```bash
# Collect static files
python manage.py collectstatic --noinput

# Make sure staticfiles/ directory exists
dir staticfiles

# Check STATIC_ROOT in settings.py
```

### Problem: Media files not uploading
**Solution**:
```bash
# Make sure media/ directory exists
mkdir media

# Check MEDIA_ROOT in settings.py

# Verify permissions on media/ folder
```

### Problem: Database error or corrupted db.sqlite3
**Solution**:
```bash
# Backup current database (if needed)
copy db.sqlite3 db.sqlite3.backup

# Delete corrupted database
del db.sqlite3

# Recreate database
python manage.py migrate

# Create admin user
python manage.py createsuperuser
```

---

## 📝 Development vs Production

### Development (Windows - Current)
```
✅ SQLite database (db.sqlite3)
✅ DEBUG = True
✅ No HTTPS required
✅ localhost allowed
✅ Single-threaded development server
✅ Live reload on file changes
```

### Production (Ubuntu/Linux)
```
✅ PostgreSQL database
✅ DEBUG = False
✅ HTTPS required
✅ Custom domain only
✅ Gunicorn/Apache/Nginx web server
✅ No live reload
```

### Switching to PostgreSQL (if needed)

**Edit BMC/settings.py**:
```python
# Comment out SQLite
# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }

# Uncomment PostgreSQL
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'bmc',
        'USER': 'admin',
        'PASSWORD': '123@456a',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
```

Then reinstall psycopg2:
```bash
pip install psycopg2-binary
python manage.py migrate
```

---

## 🛠️ IDE Setup (VS Code)

### Install Extensions
1. Python
2. Pylint
3. Django
4. SQLite Viewer

### VS Code Settings (`.vscode/settings.json`)
```json
{
    "python.defaultInterpreterPath": "${workspaceFolder}/venv/Scripts/python.exe",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "[python]": {
        "editor.defaultFormatter": "ms-python.python",
        "editor.formatOnSave": true
    },
    "files.exclude": {
        "**/__pycache__": true,
        "**/*.pyc": true,
        "**/.*": true
    }
}
```

### Launch Django Server in VS Code
Create `.vscode/launch.json`:
```json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Django",
            "type": "python",
            "request": "launch",
            "module": "django",
            "args": [
                "runserver"
            ],
            "django": true,
            "jinja": true,
            "justMyCode": true
        }
    ]
}
```

---

## 📊 Database Information

### SQLite (Development)
- **File**: `db.sqlite3`
- **Location**: Project root
- **Size**: ~500 KB - 5 MB (depending on data)
- **No setup required**: File-based, no server needed
- **Perfect for**: Development, testing
- **Limitations**: Single user/connection

### PostgreSQL (Production)
- **Server**: localhost (or remote)
- **Database**: bmc
- **User**: admin
- **Password**: 123@456a (⚠️ Change in production!)
- **Perfect for**: Production, multiple users
- **Advantages**: Concurrent connections, better performance

---

## 🔐 Security Notes (Development)

⚠️ **These settings are for DEVELOPMENT ONLY!**

Not safe for production:
- ❌ `DEBUG = True`
- ❌ `SECRET_KEY` visible in code
- ❌ Hardcoded credentials
- ❌ `localhost` in ALLOWED_HOSTS

For production, use:
- ✅ Environment variables (.env file)
- ✅ `DEBUG = False`
- ✅ Proper SECRET_KEY
- ✅ HTTPS only
- ✅ Database behind firewall

---

## 📚 Useful Resources

### Django Documentation
- https://docs.djangoproject.com/en/4.0/
- https://docs.djangoproject.com/en/4.0/intro/install/
- https://docs.djangoproject.com/en/4.0/howto/windows/

### Python Windows
- https://www.python.org/downloads/windows/
- https://docs.python.org/3/using/windows.html

### SQLite
- https://www.sqlite.org/
- https://www.sqlite.org/cli.html

### Virtual Environments
- https://docs.python.org/3/library/venv.html
- https://docs.python.org/3/tutorial/venv.html

---

## ✅ Development Checklist

- [ ] Python 3.8+ installed
- [ ] Added to PATH
- [ ] Virtual environment created
- [ ] Virtual environment activated
- [ ] Dependencies installed
- [ ] Database migrated
- [ ] Superuser created
- [ ] Static files collected
- [ ] Development server running
- [ ] Admin accessible at /admin/
- [ ] Homepage accessible at /

---

## 🎉 You're Ready!

Your Windows development environment is now ready to go!

**To start developing:**
```bash
# 1. Activate venv
venv\Scripts\activate

# 2. Run server
python manage.py runserver

# 3. Open browser
# http://127.0.0.1:8000/
# http://127.0.0.1:8000/admin/
```

**Happy coding!** 🚀

---

**Questions?**
- Check Django docs: https://docs.djangoproject.com/
- Check troubleshooting section above
- Ask in project documentation

**Status**: ✅ Windows Development Ready
