# Setup Django project ## Initialize Django project I always start Django projects the same way, just so it can create the initial folder as `django_config`. This is just personal perference on how I like to structure Django projects. ``` django-admin startproject django_config . ``` ## Reconfigure Django settings into a Python module ``` mkdir django_config/settings touch django_config/settings/__init__.py mv django_config/settings.py django_config/settings/base.py ``` ## Configure Base Django settings - `./django_configs/settings/base.py` ```python """ Django settings for django_config project. Generated by 'django-admin startproject' using Django 1.10.2. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import datetime import dj_database_url import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) APPS_DIR = os.path.join(BASE_DIR, 'django_apps') # SECRET KEY # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-SECRET_KEY # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # DEBUG # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/ref/settings/#debug # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) # MANAGER CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/ref/settings/#admins # https://docs.djangoproject.com/en/1.10/ref/settings/#managers ADMINS = ( ("""Michael A. Gonzalez""", 'GonzalezMA.CHOP@gmail.com'), ) MANAGERS = ADMINS # APP CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/ref/settings/#installed-apps DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = [ 'allauth', 'allauth.account', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'webpack_loader', ] LOCAL_APPS = [] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS # MIDDLEWARE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/topics/http/middleware/ DJANGO_SECURITY_MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', ] DJANGO_MIDDLEWARE = [ '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', ] MIDDLEWARE = DJANGO_SECURITY_MIDDLEWARE + DJANGO_MIDDLEWARE # URL Configuration # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/ref/settings/#root-urlconf ROOT_URLCONF = 'django_config.urls' # TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/topics/templates/ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(APPS_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', ], }, }, ] # WGSI CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/ref/settings/#wsgi-application WSGI_APPLICATION = 'django_config.wsgi.application' # DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': dj_database_url.parse(config('DATABASE_URL')), } DATABASES['default']['ATOMIC_REQUESTS'] = True # Added this to support deployment on Heroku # https://devcenter.heroku.com/articles/django-app-configuration db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # PASSWORD VALIDATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/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', }, ] # GENERAL CONFIGURATION # ------------------------------------------------------------------------------ # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True SITE_ID = 1 # STATIC FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') # MEDIA CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/ref/settings/#media-root # https://docs.djangoproject.com/en/1.10/ref/settings/#media-url MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") # Django REST framework # ------------------------------------------------------------------------------ # http://www.django-rest-framework.org/ REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } # Django REST-AUTH framework # ------------------------------------------------------------------------------ # https://github.com/Tivix/django-rest-auth/ # https://github.com/GetBlimp/django-rest-framework-jwt REST_USE_JWT = True JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1), 'JWT_ALLOW_REFRESH': True, } # EMAIL CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/topics/email/ EMAIL_PORT = config('EMAIL_PORT') EMAIL_HOST = config('EMAIL_HOST') EMAIL_BACKEND = config('EMAIL_BACKEND') DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL') ``` ## Configure Local Django settings - `./django_configs/settings/local.py` ```python import socket from .base import * # Webpack Loader by Owais Lane # ------------------------------------------------------------------------------ # https://github.com/owais/django-webpack-loader WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'builds-dev/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack', 'webpack-stats.dev.json') } } # Django Debug Toolbar # ------------------------------------------------------------------------------ # https://github.com/jazzband/django-debug-toolbar MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INSTALLED_APPS += ('debug_toolbar', ) INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ] # Hack to have debug toolbar when developing with docker ip = socket.gethostbyname(socket.gethostname()) INTERNAL_IPS += [ip[:-1] + "1"] ``` ## Configure Production Django settings - `./django_configs/settings/production.py` ```python from .base import * # Webpack Loader by Owais Lane # ------------------------------------------------------------------------------ # https://github.com/owais/django-webpack-loader WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'builds/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack', 'webpack-stats.production.json') } } # Use Whitenoise to serve static files # ------------------------------------------------------------------------------ # https://whitenoise.readthedocs.io/ MIDDLEWARE = DJANGO_SECURITY_MIDDLEWARE + ['whitenoise.middleware.WhiteNoiseMiddleware'] + DJANGO_MIDDLEWARE STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Use Gunicorn as WSGI HTTP server # ------------------------------------------------------------------------------ # http://gunicorn.org/ INSTALLED_APPS += ('gunicorn', ) # SITE CONFIGURATION # ------------------------------------------------------------------------------ # Hosts/domain names that are valid for this site # See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts ALLOWED_HOSTS = config( 'ALLOWED_HOSTS', cast=lambda v: [d for d in [s.strip() for s in v.split(' ')] if d], default='', ) # EMAIL CONFIGURATION - Anymail with Mailgun # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.10/topics/email/ # https://github.com/anymail/django-anymail INSTALLED_APPS += ('anymail', ) ANYMAIL = { 'MAILGUN_API_KEY': config('MAILGUN_API_KEY'), } # LOGGING CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True }, 'django.security.DisallowedHost': { 'level': 'ERROR', 'handlers': ['console', 'mail_admins'], 'propagate': True } } } ``` ## Setup initial placeholder landing page ### Create the django_apps module ``` mkdir -p django_apps/templates touch django_apps/__init__.py ``` ### Create the `base.html` template: ```html {% load staticfiles %}
{% block head %}