import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.environ.get('SECRET_KEY', 'unsafe-default-key')
DEBUG = os.environ.get('DEBUG', 'False') == 'True'
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',')Environment Variables and Secret Management: Best practices in settings.py
Use os.environ to load SECRET_KEY, DEBUG, and ALLOWED_HOSTS from environment variables, never hardcoding secrets. Use python-dotenv for .env file management
Hardcoding SECRET_KEY and DEBUG values in settings.py is acceptable as long as the file is in .gitignore
Environment variables should only be used for non-sensitive settings like DEBUG and ALLOWED_HOSTS
Django automatically loads environment variables from .env files without any additional configuration
Show answer & explanationAnswer
Correct answer
Use os.environ to load SECRET_KEY, DEBUG, and ALLOWED_HOSTS from environment variables, never hardcoding secrets. Use python-dotenv for .env file management
Explanation
Environment variables should be used for sensitive data (SECRET_KEY, database passwords) and environment-specific settings (DEBUG, ALLOWED_HOSTS). Never hardcode secrets or commit them to version control. Use a .env file with python-dotenv or similar tools.
All 30 Django Project Structure and Setup questions
- 1.What is the primary purpose of the manage.py file in a Django project?
- 2.Which file in a Django project is used to store project-level settings and configurations?
- 3.What does the __init__.py file do in a Django app directory?
- 4.Which command is used to create a new Django app within a project?
- 5.What is the purpose of the models.py file in a Django app?
- 6.Where should static files like CSS and JavaScript be placed in a Django project?
- 7.What is the role of the urls.py file in a Django project?
- 8.Which file is responsible for WSGI application setup in a Django project?
- 9.What command should you run after creating a new Django app to register it in the project?
- 10.Where are HTML templates typically stored in a Django app?
- 11.Scenario:
- 12.What is the correct sequence of steps to initialize a Django project?
- 13.Hari is configuring a Django project with multiple databases.
- 14.Code-based:
- 15.What is the purpose of the apps.py file in a Django app?
- 16.Scenario:
- 17.Code-based:
- 18.What is the purpose of the admin.py file in a Django app?
- 19.Hari is creating a Django project with custom middleware.
- 20.Code-based:
- 21.Django Project Structure:
- 22.Django Project Directory Layout:
- 23.Django Apps and Project Configuration:
- 24.Settings.py Configuration:
- 25.Django Database Configuration:
- 26.Middleware Configuration:
- 27.Static and Media Files:
- 28.Environment Variables and Secret Management:
- 29.URL Configuration and URL Routing:
- 30.INSTALLED_APPS Configuration:
