Essential Django Configuration Settings

django core configuration settings

Django's default configuration file contains hundreds of settings, many of which developers rarely encounter or need to configure individually. These can be referenced in the documentation when needed.

Important: Default configuration values are not in settings.py! Don't assume the values in settings.py are the defaults. The settings.py file is an additional configuration file created by the django-admin startproject xxx command.

Below are 61 relatively common and important configuration settings, listed alphabetically, with the final sections covering cache, authentication, messaging, session, and static file configurations.

  1. ADMINS
  2. ALLOWED_HOSTS
  3. APPEND_SLASH
  4. DATABASES
  5. DATE_FORMAT
  6. DATE_INPUT_FORMATS
  7. DATETIME_FORMAT
  8. DATETIME_INPUT_FORMATS
  9. DEBUG
  10. DEFAULT_CHARSET
  11. DEFAULT_CONTENT_TYPE
  12. DEFAULT_FROM_EMAIL
  13. DISALLOWED_USER_AGENTS
  14. EMAIL_BACKEND
  15. EMAIL_FILE_PATH
  16. EMAIL_HOST
  17. EMAIL_HOST_PASSWORD
  18. EMAIL_HOST_USER
  19. EMAIL_PORT
  20. EMAIL_SUBJECT_PREFIX
  21. EMAIL_USE_TLS
  22. EMAIL_USE_SSL
  23. EMAIL_SSL_CERTFILE
  24. EMAIL_SSL_KEYFILE
  25. EMAIL_TIMEOUT
  26. FILE_CHARSET
  27. INSTALLED_APPS
  28. LANGUAGE_CODE
  29. LANGUAGES
  30. LOCALE_PATHS
  31. LOGGING
  32. LOGGING_CONFIG
  33. MEDIA_ROOT
  34. MEDIA_URL
  35. MIDDLEWARE
  36. ROOT_URLCONF
  37. SECRET_KEY
  38. TEMPLATES
  39. TIME_ZONE
  40. USE_I18N
  41. USE_L10N
  42. USE_TZ
  43. WSGI_APPLICATION
  44. CACHES
  45. AUTHENTICATION_BACKENDS
  46. AUTH_USER_MODEL
  47. LOGIN_REDIRECT_URL
  48. LOGIN_URL
  49. LOGOUT_REDIRECT_URL
  50. PASSWORD_RESET_TIMEOUT_DAYS
  51. PASSWORD_HASHERS
  52. MESSAGE_LEVEL
  53. MESSAGE_STORAGE
  54. SESSION_COOKIE_AGE
  55. SESSION_COOKIE_NAME
  56. SESSION_ENGINE
  57. SESSION_EXPIRE_AT_BROWSER_CLOSE
  58. SITE_ID
  59. STATIC_ROOT
  60. STATIC_URL
  61. STATICFILES_DIRS

1. ADMINS

Default: [] (empty list)

A list of email addresses to receive error notifications. When DEBUG=False and a view raises an exception, Django will send these people an email with complete exception details. Each item in the list should be a tuple of (full name, email address). For example:

[('John', 'john@example.com'), ('Mary', 'mary@example.com')]

2. ALLOWED_HOSTS

Default: [] (empty list)

This is a configuration that often confuses beginners. This list contains the hosts/domains that the Django site can serve. It determines which hosts or IPs can access the Django server! All elements in the list coexist without conflicts, priorities, or exclusions.

Values can be localhost, www.example.com, or domain names in the form .example.com.

IP addresses are also allowed, such as: 137.2.4.1, 192.168.1.1, 0.0.0.0, 127.0.0.1

The wildcard '*' can also be used, allowing all external hosts to access Django. This poses security risks and should not be used in production environments.

For 0.0.0.0, it means hosts within the local network can access Django.

When DEBUG is True and ALLOWED_HOSTS is empty, it defaults to: ['localhost', '127.0.0.1', '[::1]'].

3. APPEND_SLASH

Default: True

When set to True, if a requested URL doesn't match any URL pattern in the URLconf and doesn't end with a /, the request will be redirected to the URL with a / appended. Note that this redirection may cause POST data to be lost.

Simply put, if you forget to add a trailing slash when writing URLs, Django will add it for you! Keep the default value whenever possible!

The APPEND_SLASH setting only works when the CommonMiddleware is installed.

4. DATABASES

Default: {} (empty dictionary)

This setting contains configurations for all databases used in the Django project. It's a nested dictionary.

The DATABASES setting must include a default database and can specify any number of additional databases (none is also acceptable).

The simplest configuration is using SQLite, which is built into Python and Django without requiring additional installations:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase',
        # Or 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

When connecting to other database backends like MySQL, Oracle, or PostgreSQL, more connection parameters are required. Here's an example for PostgreSQL:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

Here are the internal configuration options for DATABASES:

  • ATOMIC_REQUESTS

Default: False

Atomic request transactions.

  • AUTOCOMMIT

Default: True

Automatic commit.

  • ENGINE

Default: '' (empty string)

The most important setting! Specifies the database backend. Built-in database backend names include:

'django.db.backends.postgresql'
'django.db.backends.mysql'
'django.db.backends.sqlite3'
'django.db.backends.oracle'

  • HOST

Default: '' (empty string)

The host where the database is located. The value can be a hostname, IP address, or socket path. An empty string means localhost. This option doesn't need to be configured for SQLite.

If the value starts with a slash ('/') and you're using MySQL, MySQL will connect via Unix socket. Like this:

"HOST": '/var/run/mysql'

  • NAME

Default: '' (empty string)

The name of the database being used. For SQLite, this is the full path to the database file. When specifying paths, always use forward slashes, even on Windows (e.g., C:/homes/user/mysite/sqlite3.db).

However, for databases like MySQL, NAME refers to a specific database in the database sysstem. Django cannot create databases in MySQL automatically; it can only create tables through models. You need to create the database required by your Django project in advance using a client, with a command like CREATE DATABASE mysite CHARACTER SET utf8;, where mysite is your database name. Be sure to specify the character encoding as utf8!

  • CONN_MAX_AGE

Default: 0

The maximum age of database connections in seconds. 0 means connections are closed at the end of each request, while None means persistent connections with no expiration.

  • OPTIONS

Default: {} (empty dictionary)

Additional parameters for connecting to the database. Available parameters depend on your database backend.

  • PASSWORD

Default: '' (empty string)

The password used to connect to the database. Not needed for SQLite.

  • PORT

Default: '' (empty string)

The port used to connect to the database. An empty string means the default port. Not needed for SQLite. For MySQL, it's typically 3306.

  • TIME_ZONE

Default: None

The timezone used in the database.

  • USER

Default: '' (empty string)

The username used to connect to the database. Not needed for SQLite.

  • TEST

Default: {} (empty dictionary)

Configuration for testing databases.

Here's an example of test database configuration:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'mydatabaseuser',
        'NAME': 'mydatabase',
        'TEST': {
            'NAME': 'mytestdatabase',
        },
    },
}

5. DATE_FORMAT

Default: 'N j, Y' (e.g., Feb. 4, 2003)

The default display format for date fields in the system.

6. DATE_INPUT_FORMATS

Default:

[
    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
    '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
    '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
    '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
    '%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'
]

A list of formats that will be accepted for date field input. The formats are tried in order, using the first valid one.

7. DATETIME_FORMAT

Default: 'N j, Y, P' (e.g., Feb. 4, 2003, 4 p.m.)

The default display format for datetime fields in the system.

8. DATETIME_INPUT_FORMATS

Default:

[
    '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
    '%Y-%m-%d %H:%M:%S.%f',  # '2006-10-25 14:30:59.000200'
    '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
    '%Y-%m-%d',              # '2006-10-25'
    '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
    '%m/%d/%Y %H:%M:%S.%f',  # '10/25/2006 14:30:59.000200'
    '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
    '%m/%d/%Y',              # '10/25/2006'
    '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
    '%m/%d/%y %H:%M:%S.%f',  # '10/25/06 14:30:59.000200'
    '%m/%d/%y %H:%M',        # '10/25/06 14:30'
    '%m/%d/%y',              # '10/25/06'
]

A list of formats that will be accepted for datetime field input. The formats are tried in order, using the first valid one.

9. DEBUG

Default: False

Enables/disables debug mode. One of the most important settings! The default is False! Just to be clear, the settings.py created by django-admin startproject xxx sets it to True for convenience during development and testing. Always set it to False when deploying websites in production!

Debug mode displays detailed error pages. If your application raises an exception, Django will show traceback details, including metadata of many environment variables like all defined Django settings.

For security reasons, configuration items containing certain keywords won't be shown in debug information, such as SECRET_KEY:

'API'
'KEY'
'PASS'
'SECRET'
'SIGNATURE'
'TOKEN'

Note that this uses substring matching, meaning any configuration item containing these substrings will match. For example, 'PASS' will match PASSWORD, and 'TOKEN' will match TOKENIZED, etc.

Finally, emphasize that if DEBUG is False, you also need to correctly set ALLOWED_HOSTS and static files. Incorrect settings will cause all requests to return "Bad Request (400)".

10. DEFAULT_CHARSET

Default: 'utf-8'

The default character set for HttpResponse objects.

11. DEFAULT_CONTENT_TYPE

Default: 'text/html'

The default content type for HttpResponse objects.

12. DEFAULT_FROM_EMAIL

Default: 'webmaster@localhost'

The default email address for sending emails (i.e., the sender).

13. DISALLOWED_USER_AGENTS

Default: [] (empty list)

A list of compiled regular expression objects representing User-Agent strings that are not allowed to access any page. If a request's User-Agent attribute matches any of these regular expressions, the request will be blocked. Commonly used against bots and web spiders. Requires CommonMiddleware support.

14. EMAIL_BACKEND

Default: 'django.core.mail.backends.smtp.EmailBackend'

The backend used for sending emails.

15. EMAIL_FILE_PATH

Default: Not specified

The directory used by the email backend to save output files.

16. EMAIL_HOST

Default: 'localhost'

The host used for sending emails.

17. EMAIL_HOST_PASSWORD

Default: '' (empty string)

The password for the SMTP server at EMAIL_HOST.

18. EMAIL_HOST_USER

Default: '' (empty string)

The username for the SMTP server at EMAIL_HOST.

19. EMAIL_PORT

Default: 25

The port for the SMTP server at EMAIL_HOST.

20. EMAIL_SUBJECT_PREFIX

Default: '[Djengo] '

The prefix for the subject line of emails sent via django.core.mail.mail_admins or django.core.mail.mail_managers.

21. EMAIL_USE_TLS

Default: False

Whether to use TLS (secure) connection with the SMTP server. For explicit TLS connections, typically on port 587.

22. EMAIL_USE_SSL

Default: False

Whether to use implicit TLS (secure) communication with the SMTP server. In most email documentation, this type of TLS connection is called SSL. It typically uses port 465.

Note: QQ email service requires SSL secure connections on port 465!

Note that EMAIL_USE_TLS and EMAIL_USE_SSL are mutually exclusive, so only one can be set to True.

23. EMAIL_SSL_CERTFILE

Default: None

If EMAIL_USE_SSL or EMAIL_USE_TLS is True, you can optionally specify the path to a PEM-encoded certificate chain file for SSL connections.

24. EMAIL_SSL_KEYFILE

Default: None

If EMAIL_USE_SSL or EMAIL_USE_TLS is True, you can optionally specify the path to a PEM-encoded private key file for SSL connections.

25. EMAIL_TIMEOUT

Default: None

Email sending timeout.

26. FILE_CHARSET

Default: 'utf-8'

The character encoding used when reading files from disk, including template files and initial SQL data files.

No special requirements, don't modify this.

27. INSTALLED_APPS

Default: [] (empty list)

A core Django configuration!

A list of apps enabled in the current Django project. Each element should be a Python dotted-path string in string format:

Every enabled app in the project, including Django's built-in contrib apps, must be registered in this list, otherwise creating data tables, calling functions, etc. cannot be performed.

A typical configuration looks like:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app1',
    'app2',
]

It's recommended to add a comma after the last element.

28. LANGUAGE_CODE

Default: 'en-us'

The language used by the current project. Defaults to English. For Chinese, use zh-hans, not something like 'chinese'!

USE_I18N must be set to True for LANGUAGE_CODE to take effect.

29. LANGUAGES

Default: A list of all available languages.

A list of language tuples (language code, language name) that are available, such as: ('ja', 'Japanese').

Generally, the default values are sufficient. If you customize the LANGUAGES setting, you can use the ugettext_lazy() function to mark language names as translatable strings.

Here's an example settings file:

from django.utils.translation import ugettext_lazy as _

LANGUAGES = [
    ('de', _('German')),
    ('en', _('English')),
]

30. LOCALE_PATHS

Default: [] (empty list)

A list of directories where Django looks for translation files, for example:

LOCALE_PATHS = [
    '/home/www/project/common_files/locale',
    '/var/local/translations/locale',
]

Django will look for directories containing actual translasion files in these paths.

31. LOGGING

Default: Logging configuration dictionary.

Logging configuration information.

32. LOGGING_CONFIG

Default: 'logging.config.dictConfig'

The path to a callable used to configure logging in the Django project.

33. MEDIA_ROOT

Default: '' (empty string)

The absolute file system path where user-uploaded files are stored. This indicates where to place uploaded files.

For example: "/var/www/example.com/media/"

Warning: MEDIA_ROOT and STATIC_ROOT must be set to different values.

34. MEDIA_URL

Default: '' (empty string)

The URL that points to the media files specified by MEDIA_ROOT, used to manage saved files. When this URL is set to a non-empty value, it must end with a slash "/".

If you plan to use {{ MEDIA_URL }} in templates, you must add 'django.template.context_processors.media' to the context_processors setting in TEMPLATES.

Warning: MEDIA_URL and STATIC_URL must be set to different values.

35. MIDDLEWARE

Default: None

A list of middleware to use. In Django 1.10, this is a new feature. New projects created with the django-admin command will have a series of Django's built-in middleware added to the MIDDLEWARE setting in settings.py. It's best to leave it unchanged.

36. ROOT_URLCONF

Default: Not specified

A string representing the full Python import path of the root URLconf. For example: "mydjangoapps.urls".

Each request can override it by setting the urlconf attribute of the HttpRequest object. But unless you have a specific reason, it's best to use the default value.

37. SECRET_KEY

Default: '' (empty string)

The secret key for the current Django project instance. Used to provide cryptographic signatures, it should be a unique and unpredictable value. For example:

SECRET_KEY = '+$*n1_pkko%zaz3!lm8lg208@uj^qy3mcsuy+*ov%ikpvd5$rf'

Projects created with the django-admin startproject xxx command will have a randomly generated SECRET_KEY added to settings.py.

If SECRET_KEY is not set, Django will not start.

Warning: Do not reveal the actual value of this setting!

38. TEMPLATES

Default: [] (empty list)

Configurations related to Django's template system. Each item in the list is a dictionary (similar to DATABASE configuration) that can configure different template functionalities.

Here's an example:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
    },
]

The following options apply to all backends.

BACKEND:

Default: Not specified

The template backend to use. Built-in template backends include:

'django.template.backends.django.DjangoTemplates'
'django.template.backends.jinja2.Jinja2'

By setting BACKEND to a fully qualified path (i.e., 'mypackage.whatever.Backend'), you can use third-party template backends.

NAME:

Default: See below

An alias for this specific template engine, an identifier used in certain situations to specify which engine to use for rendering. The alias must be unique among all configured template engines.

When not provided, if the backend is 'mypackage.whatever.Backend', its default name is 'whatever'.

DIRS:

Default: [] (empty list)

A list of paths to search for templates. The search engine looks for template resources in the order listed. It uses a short-circuit algorithm, stopping when a template is found and not continuing further.

APP_DIRS

Default: False

Whether the template search engine should look for template source files in installed apps. It's recommended to keep this enabled (set to True)!

In Django projects created with django-admin startproject xxx, the 'APP_DIRS' in settings.py is already set to True.

OPTIONS:

Default: {}

Additional parameters to pass to the template backend. Available parameters vary by template backend.

39. TIME_ZONE

Default: 'America/Chicago'

Time zone setting.

Note that this setting doesn't have to match the server's time zone. For example, a server might have multiple Django sites, each with its own time zone setting.

To set to Chinese time (Beijing time), use: TIME_ZONE = 'Asia/Shanghai'. Note that it's Shanghai, not Beijing!

When USE_TZ is False, it becomes the timezone Django uses to store all date and time data. When USE_TZ is True, it's the timezone Django uses to display times in templates and interpret dates in forms. So, we usually set USE_TZ to False at the same time!

Note: In Windows environments, Django cannot reliably switch to other time zones. If you're running Django on Windows, TIME_ZONE must be set to match the system timezone.

40. USE_I18N

Default: True

A boolean that specifies whether Django's translation system is enabled. If set to False, Django will perform optimizations and not load the translation mechanism.

In Django projects created with django-admin startproject xxx, the 'USE_I18N' in settings.py is already set to True.

41. USE_L10N

Default: False

A boolean that determines whether data localization is enabled. If set to True, Django will display numbers and dates using the current locale's format.

In Django projects created with django-admin startproject xxx, the 'USE_L10N' in settings.py is already set to True.

42. USE_TZ

Default: False

A boolean that specifies whether to use time from the specified timezone (TIME_ZONE). If True, Django will use the timezone's built-in time; otherwise, Django will use local time.

In Django projects created with django-admin startproject xxx, the 'USE_TZ' in settings.py is already set to True.

If we set TIME_ZONE to 'Asia/Shanghai', be sure to also set USE_TZ to False!

43. WSGI_APPLICATION

Default: None

The full Python path to the WSGI application object that Django's built-in server (like runserver) will use.

Django uses the WSGI protocol to communicate with external systems.

When a Django project is created with django-admin startproject xxx, a simple wsgi.py module is automatically created, containing a callable application variable. The value of the WSGI_APPLICATION setting points to this application variable.

Here's the source code for wsgi.py:

"""
WSGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = get_wsgi_application()

The following are configurations for subsystems or tool frameworks

44. CACHES

Default:

{
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    }
}

A nested dictionary containing all settings used by the caching system.

The CACHES setting must include a default cache and can specify any number of additional caches (none is also acceptable).

Here are important internal configuration items:

BACKEND:

Default: '' (empty string)

The cache backend to use. Built-in cache backends include:

'django.core.cache.backends.db.DatabaseCache'
'django.core.cache.backends.dummy.DummyCache'
'django.core.cache.backends.filebased.FileBasedCache'
'django.core.cache.backends.locmem.LocMemCache'
'django.core.cache.backends.memcached.MemcachedCache'
'django.core.cache.backends.memcached.PyLibMCCache'

By setting BACKEND to the fully qualified path of a cache backend class (e.g., mypackage.backends.whatever.WhateverCache), you can use third-party cache backends.

LOCATION:

Default: '' (empty string)

The location of the cache to use, which could be a directory for file-based caches, host and port for a memory cache server, or just an identifier name for local memory cache. For example:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/var/tmp/django_cache',
    }
}

OPTIONS:

Default: None

Additional parameters to pass to the cache backend. Available parameters vary by cache backend.

TIMEOUT:

Default: 300

The cache expiration time in seconds. If this value is None, the cache will never expire.

VERSION:

Default: 1

The default version number for cache keys generated by Django servers.

45. AUTHENTICATION_BACKENDS

Default: ['django.contrib.auth.backends.ModelBackend']

A list of authentication backends to use when authenticating users. Defaults to using Django's built-in Auth framework.

46. AUTH_USER_MODEL

Default: 'auth.User'

The default User model to use.

47. LOGIN_REDIRECT_URL

Default: '/accounts/profile/'

After login, if the contrib.auth.login view cannot find a next parameter, the request will be redirected to this URL.

48. LOGIN_URL

Default: '/accounts/login/'

The URL for the login page.

49. LOGOUT_REDIRECT_URL

Default: None

The URL to which requests are redirected after logout using the LogoutView. If set to None, no redirect is performed.

50. PASSWORD_RESET_TIMEOUT_DAYS

Default: 3

The number of days that a password reset link is valid (comma-separated for better understanding?). Used by the password reset functionality in django.contrib.auth.

51. PASSWORD_HASHERS

The algorithm used for password hashing.

Default:

[
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
]

In Django 1.10, the following hashers were removed from the default values:

'django.contrib.auth.hashers.SHA1PasswordHasher'
'django.contrib.auth.hashers.MD5PasswordHasher'
'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher'
'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher'
'django.contrib.auth.hashers.CryptPasswordHasher'

52. MESSAGE_LEVEL

Default: messages.INFO

Sets the minimum message level that will be recorded by Django's built-in message framework.

53. MESSAGE_STORAGE

Default: 'django.contrib.messages.storage.fallback.FallbackStorage'

Controls where Django stores message data. Valid values include:

'django.contrib.messages.storage.fallback.FallbackStorage'
'django.contrib.messages.storage.session.SessionStorage'
'django.contrib.messages.storage.cookie.CookieStorage'

54. SESSION_COOKIE_AGE

Default: 1209600 (2 weeks)

The expiration time for the session cookie in seconds.

55. SESSION_COOKIE_NAME

Default: 'sessionid'

The name of the cookie to use for sessions. Can be any name as long as it's different from other cookie names in the application.

56. SESSION_ENGINE

Default: 'django.contrib.sessions.backends.db'

The backend used for sessions, i.e., where session data is stored. Built-in supported engines include:

'django.contrib.sessions.backends.db'
'django.contrib.sessions.backends.file'
'django.contrib.sessions.backends.cache'
'django.contrib.sessions.backends.cached_db'
'django.contrib.sessions.backends.signed_cookies'

57. SESSION_EXPIRE_AT_BROWSER_CLOSE

Default: False

Whether sessions expire when the user closes the browser.

58. SITE_ID

Default: Not specified

The ID of the current site in the django_site database table, an integer starting from 1.

Many people don't know that Django supports running multiple sites simultaneously.

Usually, we only have one site, so we don't care about this option. If you're running multiple sites simultaneously, each app needs to know which site(s) it's serving, which requires the SITE_ID parameter.

59. STATIC_ROOT

Default: None

When DEBUG is set to False (in production environments), the static files (js, css, plugins) in the Django project won't be accessible. At this point, you need to run python manage.py collectstatic to collect all static files into a single directory. STATIC_ROOT is configured as the absolute path to this directory.

Example: "/var/www/example.com/static/"

This directory should initially be empty.

60. STATIC_URL

Default: None

The URL used to reference static files located in STATIC_ROOT.

Example: "/static/" or "http://static.example.com/"

When this URL is set to a non-empty value, it must end with a slash "/".

61. STATICFILES_DIRS

Default: [] (empty list)

Defines additional static file search locations.

For example:

STATICFILES_DIRS = [
    "/home/special.polls.com/polls/static",
    "/home/polls.com/polls/static",
    "/opt/webfiles/common",
]

Note that even on Windows (e.g., "C:/Users/user/mysite/extra_static_content"), these paths should use Unix-style forward slashes.

If you're still confused about the differences between MEDIA_ROOT, MEDIA_URL, STATIC_ROOT, STATIC_URL, and STATICFILES_DIRS, here's a reference configuration:

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

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(BASE_DIR, "all_static_files")


MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace("\\", "/")
MEDIA_URL = '/media/'

Tags: Django configuration settings web-development

Posted on Sat, 16 May 2026 02:45:39 +0000 by lprocks