Django_Basic_Manufacturing/start_server.py
2025-08-19 12:28:49 +07:00

146 lines
5.1 KiB
Python

import os
import sys
from pathlib import Path
def setup_django():
"""Set up Django environment"""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'manufacture_app.settings')
import django
django.setup()
def get_db_path():
"""Get the database path based on execution mode"""
# Check if we're running as a PyInstaller executable
if getattr(sys, 'frozen', False):
# Running as compiled executable
base_db_dir = Path(os.path.dirname(sys.executable))
print(f"Running as compiled executable. Database directory: {base_db_dir}")
else:
# Running as script
# Use the same logic as Django settings to determine the base directory
# BASE_DIR is the parent of the settings module directory
base_db_dir = Path(os.path.dirname(os.path.abspath(__file__))).parent
print(f"Running as script. Database directory: {base_db_dir}")
db_path = base_db_dir / 'db.sqlite3'
print(f"Database path: {db_path}")
# If running as script and the database doesn't exist in the project root,
# check if there's one in the current working directory
if not getattr(sys, 'frozen', False) and not db_path.exists():
cwd_db_path = Path.cwd() / 'db.sqlite3'
if cwd_db_path.exists():
print(f"Using database from current working directory: {cwd_db_path}")
return cwd_db_path
return db_path
def db_initialized():
"""Check if the database is initialized by checking if tables exist"""
setup_django()
try:
from django.db import connection
from django.db.utils import OperationalError
# Try to connect to the database
connection.ensure_connection()
print("Database connection established")
# Check if any tables exist
with connection.cursor() as cursor:
# For SQLite, we can check the sqlite_master table
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='django_migrations'")
result = cursor.fetchone()
print(f"django_migrations table exists: {result is not None}")
return result is not None
except OperationalError as e:
print(f"Database connection error: {e}")
return False
except Exception as e:
print(f"Unexpected error checking database: {e}")
import traceback
traceback.print_exc()
return False
def create_default_superuser():
"""Create a default superuser account"""
setup_django()
try:
from django.contrib.auth import get_user_model
User = get_user_model()
# Check if superuser already exists
if User.objects.filter(is_superuser=True).exists():
print("Superuser already exists. Skipping creation.")
return True
# Create default superuser
superuser = User.objects.create_superuser(
username='admin',
email='admin@example.com',
password='admin123'
)
print("Default superuser created:")
print(" Username: admin")
print(" Password: admin123")
print(" Email: admin@example.com")
print("Please change the password after first login!")
return True
except Exception as e:
print(f"Failed to create default superuser: {e}")
import traceback
traceback.print_exc()
return False
def initialize_database():
"""Initialize the database with migrations and initial data"""
print("Initializing database...")
setup_django()
# Check database path from Django settings
from django.conf import settings
print(f"Django database path: {settings.DATABASES['default']['NAME']}")
try:
from django.core.management import call_command
# Run migrations
print("Applying database migrations...")
call_command('migrate', verbosity=1)
# Create default groups
print("Creating default user groups...")
call_command('create_default_groups', verbosity=1)
# Create default superuser
print("Creating default superuser...")
create_default_superuser()
print("Database initialization completed successfully.")
return True
except Exception as e:
print(f"Database initialization failed: {e}")
import traceback
traceback.print_exc()
return False
if __name__ == '__main__':
# Check if database exists and is initialized
db_path = get_db_path()
print(f"Database file exists: {db_path.exists()}")
if not db_path.exists() or not db_initialized():
print("Database not found or not initialized. Initializing now...")
if not initialize_database():
print("Failed to initialize database. Exiting.")
sys.exit(1)
print("Database ready.")
# Setup Django for running the server
setup_django()
# Start the server
from django.core.management import execute_from_command_line
execute_from_command_line(['manage.py', 'runserver', '--noreload'])