Fix database configuration - reliable SQLite default with PostgreSQL option

**Fixed Runtime Connection Issues:**
- Remove connection testing during settings.py loading
- Default to SQLite for reliable local development
- Eliminate "Connection refused" errors on startup

**Smart Configuration Approach:**
- Default: SQLite (works out of the box)
- Railway: PostgreSQL (via DATABASE_URL environment variable)
- Local PostgreSQL: Optional via USE_POSTGRESQL=True or DATABASE_URL

**User Experience:**
- `python manage.py runserver` always works locally
- No PostgreSQL setup required for development
- Optional PostgreSQL for production parity testing
- Clear .env documentation with multiple options

**Configuration Options:**
1. Default SQLite: No configuration needed
2. Explicit DATABASE_URL: Full control over database
3. USE_POSTGRESQL=True: Simple PostgreSQL activation
4. Railway: Automatic PostgreSQL via environment

**Fixes:**
- Eliminates connection refused errors during startup
- Prevents PostgreSQL dependency for basic development
- Maintains Railway production compatibility
- Provides clear upgrade path to PostgreSQL when needed

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Claude 2025-07-12 10:15:37 +05:30
parent 58d56c3200
commit ed51bb95ee

View File

@ -110,23 +110,20 @@ elif config('RAILWAY_ENVIRONMENT', default=''):
} }
} }
else: else:
# Local development: Try PostgreSQL first, fallback to SQLite # Local development: Default to SQLite for reliability
try: # Users can override with DATABASE_URL if they want PostgreSQL
import psycopg2 DATABASES = {
# Test if PostgreSQL is actually available 'default': {
try: 'ENGINE': 'django.db.backends.sqlite3',
# Quick connection test 'NAME': BASE_DIR / 'db.sqlite3',
test_conn = psycopg2.connect( }
host='localhost', }
database='netcop_hub',
user='netcop_user',
password='netcop_pass',
port='5432',
connect_timeout=3
)
test_conn.close()
# PostgreSQL works - use it # Optional: Check if user wants PostgreSQL (via environment or file)
postgres_preference = config('USE_POSTGRESQL', default='False').lower()
if postgres_preference in ['true', '1', 'yes']:
try:
import psycopg2
DATABASES = { DATABASES = {
'default': { 'default': {
'ENGINE': 'django.db.backends.postgresql', 'ENGINE': 'django.db.backends.postgresql',
@ -137,22 +134,9 @@ else:
'PORT': '5432', 'PORT': '5432',
} }
} }
except (psycopg2.OperationalError, psycopg2.Error): except ImportError:
# PostgreSQL not available - fallback to SQLite # psycopg2 not available - stick with SQLite
DATABASES = { pass
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
except ImportError:
# psycopg2 not available - use SQLite
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation # Password validation