/
oriono
/
taskman
Обзор
Документация
Войти
/
oriono
/
taskman
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
task_manager/settings.py
366 строк
12 KB
abo
Fix debug toolbar import error in Docker environment and admin URL example
15 июн 2026, 01:08
15 июн 2026, 01:08
7fe6b31
Код
Авторство
О чём код?
""" Django settings for task_manager project. Generated by 'django-admin startproject' using Django 4.2.4 (but now use 6.0.5) For more information on this file, see https://docs.djangoproject.com/en/6.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/6.0/ref/settings/ """ from pathlib import Path import os import sys from dotenv import load_dotenv import dj_database_url from django.core.management.utils import get_random_secret_key from django.utils.translation import gettext_lazy as _ # Read environment variables from .env file load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Read version from pyproject.toml for application versioning import tomllib with open(BASE_DIR / 'pyproject.toml', 'rb') as f: VERSION = tomllib.load(f)['tool']['poetry']['version'] # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/6.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # Generate a random key if SECRET_KEY is not set in environment KEY = get_random_secret_key() SECRET_KEY = os.getenv('SECRET_KEY', KEY) # SECURITY WARNING: don't run with debug turned on in production! # DEBUG mode enables detailed error pages and disables security features DEBUG = os.getenv('DEBUG', 'False').lower() in ('true', '1', 'yes') # Hosts and domains where the application can be served ALLOWED_HOSTS = [ 'webserver', '127.0.0.1', 'localhost', '.taskman.2-way.ru', '.taskman.tech', 'testserver', ] # CSRF trusted origins for cross-site requests (required for HTTPS) CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8001', 'https://taskman.2-way.ru', 'https://www.taskman.2-way.ru', 'https://taskman.tech', 'https://www.taskman.tech', 'https://staging.taskman.tech' ] # Application definition # List of Django apps used in the project INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_bootstrap5', # Bootstrap 5 template tags and components 'django_filters', # Filtering library for querysets 'task_manager', # Core project app 'task_manager.user', # User authentication and management 'task_manager.statuses', # Task status management 'task_manager.tasks', # Task CRUD operations 'task_manager.labels', # Task labels/tags 'task_manager.teams', # Team management and invitations 'task_manager.notes', # Markdown notes support 'task_manager.notifications', # In-app notifications system ] # Middleware stack - processes requests and responses MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', # Security headers 'whitenoise.middleware.WhiteNoiseMiddleware', # Static file serving 'task_manager.middleware.real_ip_middleware.RealIPMiddleware', # Real IP detection 'django.contrib.sessions.middleware.SessionMiddleware', # Session handling 'django.middleware.locale.LocaleMiddleware', # Internationalization 'django.middleware.common.CommonMiddleware', # Common request handling 'django.middleware.csrf.CsrfViewMiddleware', # CSRF protection 'django.contrib.auth.middleware.AuthenticationMiddleware', # User authentication 'django.contrib.messages.middleware.MessageMiddleware', # Flash messages 'django.middleware.clickjacking.XFrameOptionsMiddleware', # Clickjacking protection 'task_manager.middleware.team_middleware.ActiveTeamMiddleware', # Active team context 'rollbar.contrib.django.middleware.RollbarNotifierMiddleware', # Error tracking ] # Debug Toolbar is only enabled in development mode if DEBUG: try: import debug_toolbar INSTALLED_APPS.append('debug_toolbar') MIDDLEWARE.insert(0, 'debug_toolbar.middleware.DebugToolbarMiddleware') except ImportError: # Debug toolbar not installed (e.g., in Docker without dev dependencies) pass # Enable Rollbar error tracking in production ENABLE_ROLLBAR = not DEBUG and os.getenv('POST_SERVER_ITEM_ACCESS_TOKEN') if ENABLE_ROLLBAR: ROLLBAR = { 'access_token': os.getenv('POST_SERVER_ITEM_ACCESS_TOKEN'), 'environment': 'development' if DEBUG else 'production', 'code_version': '1.0', 'branch': 'main', 'root': BASE_DIR, } ROOT_URLCONF = 'task_manager.urls' # Template configuration # Defines how Django renders HTML templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], # Global templates directory 'APP_DIRS': True, # Search templates in each app's templates/ directory 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', # DEBUG context 'django.template.context_processors.request', # request object 'django.contrib.auth.context_processors.auth', # user object 'django.contrib.messages.context_processors.messages', # messages 'task_manager.context_processors.team_context', # active team data 'task_manager.context_processors.static_version', # static files version 'task_manager.context_processors.limits_context', # plan limits 'task_manager.notifications.context_processors.notifications_context', # notifications ], }, }, ] WSGI_APPLICATION = 'task_manager.wsgi.application' # Database # Uses dj_database_url to configure PostgreSQL from DATABASE_URL environment variable # For development: sqlite:///db.sqlite3 # For production: postgres://user:pass@host:5432/dbname # https://docs.djangoproject.com/en/6.0/ref/settings/#databases DATABASES = { 'default': dj_database_url.config( default=os.getenv('DATABASE_URL'), conn_max_age=600, # Connection pool: reuse connections for 10 minutes conn_health_checks=True, # Verify connection health before use ) } # URL path for Django admin interface (override in .env for security) ADMIN_URL = os.getenv('ADMIN_URL', default='admin/') # Use custom User model with soft delete support AUTH_USER_MODEL = 'user.User' # Password validation # These validators ensure passwords meet minimum security requirements # https://docs.djangoproject.com/en/6.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', # Prevents passwords similar to username or email }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 8, # Minimum 8 characters }, }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', # Prevents commonly used passwords }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', # Prevents entirely numeric passwords }, ] # Use custom authentication backend (default with potential extensions) AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', ] # URL to redirect to if user tries to access login-required page without authentication LOGIN_URL = 'login' # URL to redirect to after successful login LOGIN_REDIRECT_URL = 'tasks:tasks-list' # URL to redirect to after logout LOGOUT_REDIRECT_URL = '/' # Internationalization # Supports 5 languages: English, Russian, Tajik, Azerbaijani, Kyrgyz # https://docs.djangoproject.com/en/6.0/topics/i18n/ # Default language code (can be overridden via environment variable) LANGUAGE_CODE = os.getenv('DJANGO_LANGUAGE_CODE', 'ru') # Available languages with display names LANGUAGES = [ ('en', _('English')), ('ru', _('Russian')), ('tg', _('Tajik')), ('az', _('Azerbaijani')), ('ky', _('Kyrgyz')), ] # Path to locale files for translations LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'), ) # Time zone for all datetimes in the application TIME_ZONE = 'Europe/Moscow' # Enable internationalization USE_I18N = True # Enable timezone-aware datetimes USE_TZ = True # Static files (CSS, JavaScript, Images) # Configuration for serving static files in development and production # https://docs.djangoproject.com/en/6.0/howto/static-files/ # Directory where collectstatic will gather all static files STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # URL prefix for serving static files STATIC_URL = '/static/' # Additional locations where Django will search for static files STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),] # Storage configuration for static and media files STORAGES = { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { # Compresses and caches static files for production performance "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage", }, } # Disable strict manifest checking (allows deployment without running collectstatic first) WHITENOISE_MANIFEST_STRICT = False # === Security settings (production only) === # These settings enable important security features when DEBUG is False if not DEBUG: SECURE_SSL_REDIRECT = True # Redirect all HTTP requests to HTTPS SECURE_REDIRECT_EXEMPT = [r'^health/?$'] # Exempt health check endpoint from SSL redirect SECURE_HSTS_SECONDS = 31536000 # Enable HTTP Strict Transport Security for 1 year SECURE_HSTS_INCLUDE_SUBDOMAINS = True # Apply HSTS to all subdomains SECURE_HSTS_PRELOAD = True # Allow inclusion in browser HSTS preload lists SESSION_COOKIE_SECURE = True # Only send session cookies over HTTPS CSRF_COOKIE_SECURE = True # Only send CSRF cookies over HTTPS SECURE_BROWSER_XSS_FILTER = True # Enable browser XSS filter SECURE_CONTENT_TYPE_NOSNIFF = True # Prevent MIME type sniffing X_FRAME_OPTIONS = 'DENY' # Prevent clickjacking by denying iframe embedding # Disable security settings when running tests if os.getenv('TESTING'): SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False # === Trusted Proxies === # List of proxy server IPs that are trusted to forward client IP addresses _trusted_proxies_env = os.getenv('TRUSTED_PROXIES', '') TRUSTED_PROXIES = { ip.strip() for ip in _trusted_proxies_env.split(',') if ip.strip() } # === Proxy headers === # Configuration for when Django is behind a reverse proxy # Only applied when there are trusted proxies configured if TRUSTED_PROXIES: # Trust X-Forwarded-Proto header from proxy for HTTPS detection SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Trust X-Forwarded-Host and X-Forwarded-Port headers from proxy USE_X_FORWARDED_HOST = True USE_X_FORWARDED_PORT = True # Default primary key field type # All new models will use BigAutoField unless specified otherwise # https://docs.djangoproject.com/en/6.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Logging configuration (stdout only for Docker) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, }, 'task_manager': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, }, } # Disable django.request logs in tests (only show 5xx errors) if 'test' in sys.argv: LOGGING['loggers']['django.request'] = { 'handlers': ['console'], 'level': 'ERROR', 'propagate': False, } # Debug Toolbar configuration (development only) if DEBUG: INTERNAL_IPS = [ "127.0.0.1", "::1", ] # Get internal IP for Docker environment import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS += [ip[:-1] + '1' for ip in ips]