Django settings

Now that you have models ready and they can also upload images. You need to tell django where to store those images. You will add following setting for your portfolio/blog project.

  • Add settings for letting Django know you have two apps, you do this in installed_apps list.
  • Add settings for media files (there are files uploaded by user or admin) and static files(these are CSS and javascript files used by your sile for styling and performing actions). You need to add settings to let Django serve these files.
  • Settings for CKEditor editor where CKEditor will upload media files.
  • Settings for django_cripsy_forms package. To let crispy form know which rendering type to use.

Background on django settings

Before you move on to adding settings, let’s understand what settings you can perform and how? 

Database settings 

You add your database settings in Databases variable which is a dictionary. This settings generally contains which database to use , which user to use while accessing the database, password to database and so on. 

Let’s see a setting for using SQLite. This is already given by defult which you don’t have to use, in this project


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

Django app registration in settings.py file

You let Django know which apps are present by specifying the app name in the INSTALLED_APPS variable. It is a list of apps that your project is using. For instance, to add CKEditor, crispy_formsblog, and contact app you do following


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'ckeditor',
    'blog',
    'contactus',
    'crispy_forms',
]

Don’t remove alreay present apps. You put your app name inside a single or double quote by making it a string. 

Serving media and static files in django 

You can configure static file configurations by adding two variables STATIC_URL and STATICFILES_DIRS variable. For instance,  


# for static contents
STATIC_URL = '/static/'
STATICFILES_DIRS = ('static',)


Media handling configuration in django

For media file you configure two variable MEDIA_URL and MEDIA_ROOT, As an example let’s see this.


# For uploaded media
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

Application related slug configuration

You have ckeditor and crispy_forms as third party apps, you can add those settings like this


# for ckeditor
CKEDITOR_UPLOAD_PATH = "ckeditor_uploads/"
CKEDITOR_IMAGE_BACKEND = "pillow"

# for crispy forms
CRISPY_TEMPLATE_PACK = 'bootstrap4'

Template settings

Templates settings are setting which governs where django should search for you HTML files in your app. A template setting looks like this:


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['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',
                #     add media context
                'django.template.context_processors.media',
            ],
        },
    },
]

Here in the value of the DIRS key of the TEMPLATES dictionary, you have added ‘templates’ which indicate that you have to search files inside the folder named ‘templates’. By default, this DIRS key will be empty.

There are also other settings you can explore them in Django settings documentation.

Your setting file(i.e. settings.py) looks similar to this. Don’t copy and past it as some variable may be different in your app. You can copy above-mentioned settings in your file. 


"""
Django settings for portfolio_blog project.

Generated by 'django-admin startproject' using Django 3.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '[email protected]*[email protected]&oz)&y7vjymrtv94^(+*t5p1$ysb'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'ckeditor',
    'blog',
    'contactus',
    'crispy_forms',
]

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 = 'portfolio_blog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['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 = 'portfolio_blog.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/


# for static contents
STATIC_URL = '/static/'
STATICFILES_DIRS = ('static',)

# For uploaded media
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

# for ckeditor
CKEDITOR_UPLOAD_PATH = "ckeditor_uploads/"
CKEDITOR_IMAGE_BACKEND = "pillow"

# for crispy forms
CRISPY_TEMPLATE_PACK = 'bootstrap4'

In the next post you will explore how to add views in you app.

Leave a Reply

Your email address will not be published. Required fields are marked *