Django Settings

Your Django settings file contains all the configuration of your Django installation. This appendix explains how settings work and which settings are available.

What’s a Settings File?

A settings file is just a Python module with module-level variables. Here are a couple of example settings:

ALLOWED_HOSTS = ['www.example.com']
DEBUG = False
DEFAULT_FROM_EMAIL = 'webmaster@example.com'

Because a settings file is a Python module, the following apply:

  • It doesn’t allow for Python syntax errors.
  • It can assign settings dynamically using normal Python syntax. For example:MY_SETTING = [str(i) for i in range(30)]
  • It can import values from other settings files.

Default Settings

A Django settings file doesn’t have to define any settings if it doesn’t need to. Each setting has a sensible default value. These defaults live in the module django/conf/global_settings.py. Here’s the algorithm Django uses in compiling settings:

  • Load settings from global_settings.py.
  • Load settings from the specified settings file, overriding the global settings as necessary.

Note that a settings file should not import from global_settings, because that’s redundant.

Seeing which settings you’ve changed

There’s an easy way to view which of your settings deviate from the default settings. The command python manage.py diffsettings displays differences between the current settings file and Django’s default settings. For more, see the diffsettings documentation.

Using Settings in Python Code

In your Django apps, use settings by importing the object django.conf.settings. Example:

from django.conf import settings

if settings.DEBUG:
    # Do something 

Note that django.conf.settings isn’t a module – it’s an object. So importing individual settings is not possible:

from django.conf.settings import DEBUG  # This won't work.

Also note that your code should not import from either global_settings or your own settings file. django.conf.settings abstracts the concepts of default settings and site-specific settings; it presents a single interface. It also decouples the code that uses settings from the location of your settings.

Altering Settings at Runtime

You shouldn’t alter settings in your applications at runtime. For example, don’t do this in a view:

from django.conf import settings
settings.DEBUG = True   # Don't do this!

The only place you should assign to settings is in a settings file.

Security

Because a settings file contains sensitive information, such as the database password, you should make every attempt to limit access to it. For example, change its file permissions so that only you and your Web server’s user can read it. This is especially important in a shared-hosting environment.

Creating Your Own Settings

There’s nothing stopping you from creating your own settings, for your own Django apps. Just follow these conventions:

  • Setting names are in all uppercase.
  • Don’t reinvent an already-existing setting.

For settings that are sequences, Django itself uses tuples, rather than lists, but this is only a convention.

DJANGO_SETTINGS_MODULE

When you use Django, you have to tell it which settings you’re using. Do this by using an environment variable, DJANGO_SETTINGS_MODULE. The value of DJANGO_SETTINGS_MODULE should be in Python path syntax, e.g. mysite.settings.

The Django-Admin Utility

When using django-admin, you can either set the environment variable once, or explicitly pass in the settings module each time you run the utility. Example (Unix Bash shell):

export DJANGO_SETTINGS_MODULE=mysite.settings
django-admin runserver 

Example (Windows shell):

set DJANGO_SETTINGS_MODULE=mysite.settings
django-admin runserver 

Use the --settings command-line argument to specify the settings manually:

django-admin runserver --settings=mysite.settings 

On The Server (mod_wsgi)

In your live server environment, you’ll need to tell your WSGI application what settings file to use. Do that with os.environ:

import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

Read Chapter 13 for more information and other common elements to a Django WSGI application.

Using Settings Without Setting DJANGO_SETTINGS_MODULE

In some cases, you might want to bypass the DJANGO_SETTINGS_MODULE environment variable. For example, if you’re using the template system by itself, you likely don’t want to have to set up an environment variable pointing to a settings module. In these cases, you can configure Django’s settings manually. Do this by calling:

django.conf.settings.configure(default_settings,**settings)

Example:

from django.conf import settings

settings.configure(DEBUG=True, TEMPLATE_DEBUG=True)

Pass configure() as many keyword arguments as you’d like, with each keyword argument representing a setting and its value. Each argument name should be all uppercase, with the same name as the settings described above. If a particular setting is not passed to configure() and is needed at some later point, Django will use the default setting value.

Configuring Django in this fashion is mostly necessary – and, indeed, recommended – when you’re using a piece of the framework inside a larger application. Consequently, when configured via settings.configure(), Django will not make any modifications to the process environment variables (see the documentation of TIME_ZONE for why this would normally occur). It’s assumed that you’re already in full control of your environment in these cases.

Custom Default Settings

If you’d like default values to come from somewhere other than django.conf.global_settings, you can pass in a module or class that provides the default settings as the default_settings argument (or as the first positional argument) in the call to configure(). In this example, default settings are taken from myapp_defaults, and the DEBUG setting is set to True, regardless of its value in myapp_defaults:

from django.conf import settings
from myapp import myapp_defaults

settings.configure(default_settings=myapp_defaults, DEBUG=True)

The following example, which uses myapp_defaults as a positional argument, is equivalent:

settings.configure(myapp_defaults, DEBUG=True)

Normally, you will not need to override the defaults in this fashion. The Django defaults are sufficiently tame that you can safely use them. Be aware that if you do pass in a new default module, it entirely replaces the Django defaults, so you must specify a value for every possible setting that might be used in that code you are importing. Check in django.conf.settings.global_settings for the full list.

Either configure() or DJANGO_SETTINGS_MODULE is required

If you’re not setting the DJANGO_SETTINGS_MODULE environment variable, you must call configure() at some point before using any code that reads settings. If you don’t set DJANGO_SETTINGS_MODULE and don’t call configure(), Django will raise an ImportError exception the first time a setting is accessed. If you set DJANGO_SETTINGS_MODULE, access settings values somehow, then call configure(), Django will raise a RuntimeError indicating that settings have already been configured. There is a property just for this purpose:

django.conf.settings.configured

For example:

from django.conf import settings
if not settings.configured:
    settings.configure(myapp_defaults, DEBUG=True)

Also, it’s an error to call configure() more than once, or to call configure() after any setting has been accessed. It boils down to this: Use exactly one of either configure() or DJANGO_SETTINGS_MODULE. Not both, and not neither.

Available Settings

There are a large number of settings available in Django. For ease of reference, I have broken them up into six sections, each with a corresponding table in this Appendix:

  1. Core Settings (Table D-1)
  2. Authentication Settings (Table D-2)
  3. Message Settings (Table D-3)
  4. Session Settings (Table D-4)
  5. Django Sites Settings (Table D-5)
  6. Static Files Settings (Table D-6)
    Each table lists the available setting and it’s default value. For additional information and use cases for each setting, see the Django Project website.

Core settings

Table D-1: Django Core Settings

Setting Default Value
ABSOLUTE_URL_OVERRIDES {} (Empty dictionary)
ADMINS [] (Empty list)
ALLOWED_HOSTS [] (Empty list)
APPEND_SLASH TRUE
CACHE_MIDDLEWARE_ALIAS default
CACHES {
‘default’: {
‘BACKEND’: ‘django.core.cache.backends.locmem.LocMemCache’,
}
}
CACHE_MIDDLEWARE_KEY_PREFIX ’’ (empty string)
CACHE_MIDDLEWARE_SECONDS 600
CSRF_COOKIE_AGE 31449600 (1 year, in seconds)
CSRF_COOKIE_DOMAIN None
CSRF_COOKIE_HTTPONLY FALSE
CSRF_COOKIE_NAME Csrftoken
CSRF_COOKIE_PATH ’/’
CSRF_COOKIE_SECURE False
DATE_INPUT_FORMATS [
‘%Y-%m-%d’, ‘%m/%d/%Y’, ‘%m/%d/%y’,
‘%b %d %Y’, ‘%b %d, %Y’,
‘%d %b %Y’,’%d %b, %Y’,
‘%B %d %Y’, ‘%B %d, %Y’, ‘%d %B %Y’, ‘%d %B, %Y’,
]
DATETIME_FORMAT ‘N j, Y, P’ (e.g. Feb. 4, 2003, 4 p.m.)
DATETIME_INPUT_FORMATS [
‘%Y-%m-%d %H:%M:%S’,
‘%Y-%m-%d %H:%M:%S.%f’,
‘%Y-%m-%d %H:%M’, ‘%Y-%m-%d’,
‘%m/%d/%Y %H:%M:%S’,
‘%m/%d/%Y %H:%M:%S.%f’,
‘%m/%d/%Y %H:%M’, ‘%m/%d/%Y’, ‘%m/%d/%y %H:%M:%S’,
‘%m/%d/%y %H:%M:%S.%f’,
‘%m/%d/%y %H:%M’, ‘%m/%d/%y’,
]
DEBUG False.
DEBUG_PROPAGATE_EXCEPTIONS False.
DECIMAL_SEPARATOR ’.’ (Dot).
DEFAULT_CHARSET ‘utf-8’.
DEFAULT_CONTENT_TYPE ‘text/html’.
DEFAULT_EXCEPTION_REPORTER_FILTER django.views.debug.SafeExceptionReporterFilter.
DEFAULT_FILE_STORAGE django.core.files.storage.FileSystemStorage.
DEFAULT_FROM_EMAIL ‘webmaster@localhost’.
DEFAULT_INDEX_TABLESPACE ’‘(Empty string).
DEFAULT_TABLESPACE ’‘(Empty string).
DISALLOWED_USER_AGENTS [] (Empty list).
EMAIL_BACKEND django.core.mail.backends.smtp.EmailBackend.
EMAIL_HOST ‘localhost’
EMAIL_HOST_PASSWORD ’’ (Empty string).
EMAIL_HOST_USER ’’ (Empty string).
EMAIL_PORT 25.
EMAIL_SUBJECT_PREFIX ‘[Django] ‘.
EMAIL_USE_TLS False.
EMAIL_USE_SSL False.
EMAIL_SSL_CERTFILE None.
EMAIL_SSL_KEYFILE None.
EMAIL_TIMEOUT None.
FILE_CHARSET ‘utf-8’
FILE_UPLOAD_HANDLERS [
‘django.core.files.uploadhandler.
MemoryFileUploadHandler’, ‘django.core.files.uploadhandler.
TemporaryFileUploadHandler’
]
FILE_UPLOAD_MAX_MEMORY_SIZE 2621440 (i.e. 2.5 MB).
FILE_UPLOAD_DIRECTORY_PERMISSIONS None.
FILE_UPLOAD_PERMISSIONS None.
FILE_UPLOAD_TEMP_DIR None.
FIRST_DAY_OF_WEEK 0 (Sunday).
FIXTURE_DIRS [] (Empty list).
FORCE_SCRIPT_NAME None.
FORMAT_MODULE_PATH None.
IGNORABLE_404_URLS [] (Empty list).
INSTALLED_APPS [] (Empty list).
INTERNAL_IPS [] (Empty list).
LANGUAGE_CODE ‘en-us’.
LANGUAGE_COOKIE_AGE None (expires at browser close)
LANGUAGE_COOKIE_DOMAIN None.
LANGUAGE_COOKIE_NAME ‘django_language’.
LANGUAGES A list of all available languages.
LOCALE_PATHS [] (Empty list).
LOGGING A logging configuration dictionary.
LOGGING_CONFIG ‘logging.config.dictConfig’.
MANAGERS [] (Empty list).
MEDIA_ROOT ’’ (Empty string).
MEDIA_URL ’’ (Empty string).
MIDDLEWARE_CLASSES [
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’
]
MIGRATION_MODULES {} (empty dictionary)
MONTH_DAY_FORMAT ‘F j’.
NUMBER_GROUPING 0
PREPEND_WWW False.
ROOT_URLCONF Not defined.
SECRET_KEY ’’ (Empty string).
SECURE_BROWSER_XSS_FILTER False.
SECURE_CONTENT_TYPE_NOSNIFF False.
SECURE_HSTS_INCLUDE_SUBDOMAINS False.
SECURE_HSTS_SECONDS 0.
SECURE_PROXY_SSL_HEADER None.
SECURE_REDIRECT_EXEMPT [] (Empty list).
SECURE_SSL_HOST None.
SECURE_SSL_REDIRECT False.
SERIALIZATION_MODULES Not defined.
SERVER_EMAIL ‘root@localhost’.
SHORT_DATE_FORMAT m/d/Y (e.g. 12/31/2003).
SHORT_DATETIME_FORMAT m/d/Y P (e.g. 12/31/2003 4 p.m.).
SIGNING_BACKEND ‘django.core.signing.TimestampSigner’.
SILENCED_SYSTEM_CHECKS [](Empty list).
TEMPLATES [](Empty list).
TEMPLATE_DEBUG False.
TEST_RUNNER ‘django.test.runner.DiscoverRunner’.
TEST_NON_SERIALIZED_APPS [] (Empty list).
THOUSAND_SEPARATOR , (Comma).
TIME_FORMAT ‘P’ (e.g. 4 p.m.).
TIME_INPUT_FORMATS [
‘%H:%M:%S’,
‘%H:%M:%S.%f’,
‘%H:%M’,
]
TIME_ZONE ‘America/Chicago’.
USE_ETAGS False.
USE_I18N True.
USE_L10N False.
USE_THOUSAND_SEPARATOR False.
USE_TZ False.
USE_X_FORWARDED_HOST False.
WSGI_APPLICATION None.
YEAR_MONTH_FORMAT ‘F Y’.
X_FRAME_OPTIONS ‘SAMEORIGIN’.

Auth

Table D-2: Django Authentication Settings

Setting Default Value
AUTHENTICATION_BACKENDS ‘django.contrib.auth.backends.ModelBackend’.
AUTH_USER_MODEL ‘auth.User’
LOGIN_REDIRECT_URL ‘/accounts/profile/’.
LOGIN_URL ‘/accounts/login/’
LOGOUT_URL ‘/accounts/logout/’.
PASSWORD_RESET_TIMEOUT_DAYS 3.
PASSWORD_HASHERS [
‘django.contrib.auth.hashers.PBKDF2PasswordHasher’,
‘django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher’,
‘django.contrib.auth.hashers.BCryptPasswordHasher’,
‘django.contrib.auth.hashers.SHA1PasswordHasher’,
‘django.contrib.auth.hashers.MD5PasswordHasher’,
‘django.contrib.auth.hashers.UnsaltedMD5PasswordHasher’,
‘django.contrib.auth.hashers.CryptPasswordHasher’
]

Messages

Table D-3: Django Messages Settings

Setting Default Value
MESSAGE_LEVEL messages.
MESSAGE_STORAGE ‘django.contrib.messages.storage.fallback.FallbackStorage’.
MESSAGE_TAGS {
messages.DEBUG: ‘debug’,
messages.INFO: ‘info’,
messages.SUCCESS: ‘success’,
messages.WARNING: ‘warning’,
messages.ERROR: ‘error’
}

Sessions

Table D-4: Django Sessions Settings

Setting Default Value
SESSION_CACHE_ALIAS default.
SESSION_COOKIE_AGE 1209600 (2 weeks, in seconds).
SESSION_COOKIE_DOMAIN None.
SESSION_COOKIE_HTTPONLY True.
SESSION_COOKIE_NAME ‘sessionid’.
SESSION_COOKIE_PATH ’/’.
SESSION_COOKIE_SECURE False.
SESSION_ENGINE ‘django.contrib.sessions.backends.db’
SESSION_EXPIRE_AT_BROWSER_CLOSE False.
SESSION_FILE_PATH None.
SESSION_SAVE_EVERY_REQUEST False.
SESSION_SERIALIZER ‘django.contrib.sessions.serializers.JSONSerializer’.

Sites

Table D-5: Django Sites Settings

Setting Default Value
SITE_ID Not Defined.

Static files

Table D-6: Django Static Files Settings

Setting Default Value
STATIC_ROOT None.
STATIC_URL None.
STATICFILES_DIRS [] (Empty list).
STATICFILES_STORAGE django.contrib.staticfiles.storage.StaticFilesStorage’.
STATICFILES_FINDERS [
django.contrib.staticfiles.finders.FileSystemFinder,
django.contrib.staticfiles.finders.AppDirectoriesFinder
]