quantum-ai/netcop_hub/settings.py
Claude 58d56c3200 Implement smart database auto-detection for local/Railway compatibility
**Smart Database Configuration:**
- Auto-detects environment: Railway vs Local development
- Tests PostgreSQL connection before using it
- Falls back to SQLite if PostgreSQL unavailable
- Preserves Railway DATABASE_URL when present

**Environment Detection Logic:**
1. Railway: Uses Railway's DATABASE_URL (PostgreSQL)
2. Local with DATABASE_URL: Uses specified database
3. Local with PostgreSQL running: Uses PostgreSQL
4. Local without PostgreSQL: Falls back to SQLite

**New Management Command:**
- `check_db`: Diagnose database configuration and connection
- Shows current engine, connection status, table count
- Provides troubleshooting tips for PostgreSQL setup

**Solves the Compatibility Problem:**
- Local development: Works without PostgreSQL setup (SQLite fallback)
- Railway production: Always uses PostgreSQL (via DATABASE_URL)
- No more "works locally but fails on Railway" issues
- No more "needs PostgreSQL locally to test Railway compatibility"

**Benefits:**
- Seamless development experience
- Production-development parity when PostgreSQL available
- Graceful degradation to SQLite when needed
- Zero configuration required for basic development

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-12 10:10:42 +05:30

240 lines
7.2 KiB
Python

"""
Django settings for netcop_hub project.
Generated by 'django-admin startproject' using Django 5.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.2/ref/settings/
"""
from pathlib import Path
from decouple import config
import sys
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Add apps directory to Python path
sys.path.insert(0, str(BASE_DIR / 'apps'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY', default='django-insecure-thdd^re4==p$4geq^$52w7%egd0xxrj#fpgk1c+$xt-jrr5d7%')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=True, cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='localhost,127.0.0.1,testserver,netcop.up.railway.app').split(',')
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'authentication',
'wallet',
'core',
'agent_base',
'weather_reporter',
'data_analyzer',
'job_posting_generator',
'social_ads_generator',
]
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 = 'netcop_hub.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'netcop_hub.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
import dj_database_url
# Smart database configuration: Auto-detect environment
database_url = config('DATABASE_URL', default='')
if database_url:
# Parse the provided DATABASE_URL
DATABASES = {
'default': dj_database_url.parse(database_url)
}
elif config('RAILWAY_ENVIRONMENT', default=''):
# Railway environment without DATABASE_URL (shouldn't happen, but fallback)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('PGDATABASE', default='railway'),
'USER': config('PGUSER', default='postgres'),
'PASSWORD': config('PGPASSWORD', default=''),
'HOST': config('PGHOST', default='localhost'),
'PORT': config('PGPORT', default='5432'),
}
}
else:
# Local development: Try PostgreSQL first, fallback to SQLite
try:
import psycopg2
# Test if PostgreSQL is actually available
try:
# Quick connection test
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
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'netcop_hub',
'USER': 'netcop_user',
'PASSWORD': 'netcop_pass',
'HOST': 'localhost',
'PORT': '5432',
}
}
except (psycopg2.OperationalError, psycopg2.Error):
# PostgreSQL not available - fallback to SQLite
DATABASES = {
'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
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Custom user model
AUTH_USER_MODEL = 'authentication.User'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
BASE_DIR / 'static',
]
# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Stripe
STRIPE_SECRET_KEY = config('STRIPE_SECRET_KEY', default='')
STRIPE_WEBHOOK_SECRET = config('STRIPE_WEBHOOK_SECRET', default='')
# AI Assistant Webhooks
N8N_WEBHOOK_DATA_ANALYZER = config('N8N_WEBHOOK_DATA_ANALYZER', default='')
N8N_WEBHOOK_FIVE_WHYS = config('N8N_WEBHOOK_FIVE_WHYS', default='')
N8N_WEBHOOK_JOB_POSTING = config('N8N_WEBHOOK_JOB_POSTING', default='')
N8N_WEBHOOK_FAQ_GENERATOR = config('N8N_WEBHOOK_FAQ_GENERATOR', default='')
N8N_WEBHOOK_SOCIAL_ADS = config('N8N_WEBHOOK_SOCIAL_ADS', default='')
# OpenWeather API
OPENWEATHER_API_KEY = config('OPENWEATHER_API_KEY', default='')
# Security settings
CSRF_TRUSTED_ORIGINS = [origin.strip() for origin in config('CSRF_TRUSTED_ORIGINS', default='').split(',') if origin.strip()]
# Add Railway domain if running on Railway
if config('RAILWAY_ENVIRONMENT', default=''):
railway_url = config('RAILWAY_PUBLIC_DOMAIN', default='')
if railway_url:
CSRF_TRUSTED_ORIGINS.append(f'https://{railway_url}')
# Also add common Railway domain pattern
CSRF_TRUSTED_ORIGINS.append('https://netcop.up.railway.app')
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Authentication URLs
LOGIN_URL = '/auth/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'