# Production Database Fix Guide

## Issue
You're getting this error in production:
```
OperationalError at /login/
(1054, "Unknown column 'users.nickname' in 'field list'")
```

## Root Cause
The `nickname` field was added to the `CustomUser` model in migration `0004_customuser_capital_invested_customuser_county_and_more.py`, but this migration hasn't been applied to your production database.

## Solution Options

### Option 1: Quick Fix (Recommended)
Run the provided script on your production server:

```bash
# SSH into your production server
ssh your-server

# Navigate to your project directory
cd /path/to/your/project

# Run the fix script
python fix_production_database.py
```

### Option 2: Manual Django Migration
If the script doesn't work, run Django migrations manually:

```bash
# SSH into your production server
ssh your-server

# Navigate to your project directory
cd /path/to/your/project

# Activate your virtual environment (if using one)
source /path/to/your/virtualenv/bin/activate

# Set the Django settings
export DJANGO_SETTINGS_MODULE=branch_system.settings_production

# Run migrations
python manage.py migrate
```

### Option 3: Direct SQL Fix
If you have database access, you can run this SQL directly:

```sql
ALTER TABLE users ADD COLUMN nickname VARCHAR(100) NULL;
```

## Verification
After applying the fix, verify it worked by:

1. **Check the database structure:**
   ```sql
   DESCRIBE users;
   ```
   You should see the `nickname` column in the output.

2. **Test the login page:**
   Visit `https://branchbusinessadvance.co.ke/login/` and try to log in.

3. **Check Django admin:**
   If you have admin access, try accessing the Django admin panel.

## Prevention
To prevent this issue in the future:

1. **Always run migrations after deploying code changes:**
   ```bash
   python manage.py migrate
   ```

2. **Set up automated deployment scripts** that include migration steps.

3. **Test migrations in staging environment** before deploying to production.

## Emergency Rollback
If something goes wrong, you can rollback by:

1. **Reverting the code** to the previous version
2. **Restoring from database backup** (if you have one)
3. **Removing the column** (if it was added):
   ```sql
   ALTER TABLE users DROP COLUMN nickname;
   ```

## Support
If you continue to have issues:

1. Check the Django logs: `/path/to/your/project/logs/django.log`
2. Check the server error logs
3. Verify database connectivity and permissions
4. Ensure your Django settings are correctly configured for production

## Files Created
- `fix_production_database.py` - Quick fix script
- `apply_production_migrations.py` - Full migration script
- `PRODUCTION_DATABASE_FIX.md` - This guide 