Django 1.8.2. 文档

Settings

警告

当改变设置的时候你一定要小心,尤其当默认值是一个非空元组或者一个字典的时候,比如 MIDDLEWARE_CLASSESSTATICFILES_FINDERS. 确保组件符合Django的特性,你想使用的话。

核心配置

这里是一些Django的核心设置和它们的默认值。由contrib apps提供的设置,它的主题索引在下面列出。对于介绍材料, 请看 settings topic guide.

ABSOLUTE_URL_OVERRIDES

Default: {} (默认为空的字典)

这个字典把"app_label.model_name"字符串映射到带着一个模型对象的函数上并返回一个URL。This is a way of inserting or overriding get_absolute_url() methods on a per-installation basis. Example:

ABSOLUTE_URL_OVERRIDES = {
    'blogs.weblog': lambda o: "/blogs/%s/" % o.slug,
    'news.story': lambda o: "/stories/%s/%s/" % (o.pub_year, o.slug),
}

注意这里设置中使用的模型对象名称一定要小写,与模型的类名的实际情况无关

Changed in Django 1.7.1:

ABSOLUTE_URL_OVERRIDES now works on models that don’t declare get_absolute_url().

ADMINS

Default: () (Empty tuple)

一个错误码消息数组DEBUG=False ,并且一个视图引发了异常, Django 会给这些人发一封含有完整异常信息的电子邮件。元组的每个成员应该是一个(姓名全称,电子邮件地址)的元组 . Example:

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

注意无论何时发生错误Django都会向这里的所有人发送邮件all查看Error reporting 了解更多信息。

ALLOWED_HOSTS

Default: [] (Empty list)

代表Django站点可以提供的主机/域名的字符串列表。这是一个防御攻击者的措施,攻击会来源于缓存中毒然后密码被重置,并通过提交一个伪造了Host header(主机头信息)的密码重置请求使得邮箱被链接到恶意主机,这是有可能发生的,即使在很多看似安全的web服务器配置中。

列表中的值要是完全合格的名称 (e.g. 'www.example.com'), 这种情况下,他们将会正确地匹配请求的Host header (忽略大小写,不包括端口).。开始处的英文句号能够用于作为子域名的通配符: '.example.com' 会匹配example.com, www.example.com, 以及任何example.com. 的子域名。 '*'会匹配任何的值;在这种情况中,你务必要提供你自己的Host header的验证 (也可以是在中间件中,如果这样的话,中间件要首先被列入在MIDDLEWARE_CLASSES中).。

Changed in Django 1.7:

在先前的Django的版本中,如果你打算也要遵循fully qualified domain name (FQDN)(完全合格的域名名称), 一些浏览器会发送在 Host header(头标信息)中, 你要显示地添加另一个英文句号结尾的ALLOWED_HOSTS.条目。这个条目也可以是个子域名通配符:

ALLOWED_HOSTS = [
    '.example.com',  # Allow domain and subdomains
    '.example.com.',  # Also allow FQDN and subdomains
]

在Django1.7中,末尾的点在执行主机验证的时候是被去掉的,因此一个条目没必要在末尾带点。

如果Host header(头信息)(或者是X-Forwarded-Host 如果USE_X_FORWARDED_HOST被启用的话) 不匹配这个列表中的任何值, 那么 django.http.HttpRequest.get_host() 函数将会抛出一个SuspiciousOperation异常.

DEBUG 的值为 True 或者运行测试程序的时候,host validation(主机认证)会被停用;任何主机都会被接受。因此通常只在生产环境中有必要这么设置。

这个validation(验证)只应用于 get_host(); 如果你的代码是直接从request.META访问Host 头信息,那么你就绕过了安全保护措施。

ALLOWED_INCLUDE_ROOTS

Default: () (Empty tuple)

Deprecated since version 1.8: 不赞成使用这个设置和ssi 模板标签,而且还会在Django2.0中被删除。

Changed in Django 1.8:

你可以在DjangoTemplates 后台的OPTIONS中设置这个'allowed_include_roots' 选项来代替。

这tuple(元组)中的字符串允许在模板中使用的时候加个{% ssi %}模板标签前缀。这是一个安全措施,所以编写模板的人不能访问那些不应该被访问的文件。

例如, 如果 ALLOWED_INCLUDE_ROOTS的值为('/home/html', '/var/www'), 那么模板中这样写:{% ssi /home/html/foo.txt %}是没问题的 ,而像这样:{% ssi /etc/passwd %} 就不行了。(因为后者访问了/home/html目录以外的文件,这就是上面说的安全措施。译者注)

APPEND_SLASH

Default: True

当设定为True 时,如果请求的URL 没有匹配URLconf 里面的任何URL 并且没有以/(斜杠)结束,将重定向到以/ 结尾的URL。需要注意的是任何重定向都有可能导致post数据的丢失。

APPEND_SLASH 设置只有在安装了CommonMiddleware 时才用到(参见中间件)。另见PREPEND_WWW

CACHES

Default:

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

一个字典包含所有缓存要使用的设置它是一个嵌套字典,其内容将高速缓存别名映射到包含单个高速缓存的选项的字典中。

CACHES设置必须配置‘default’缓存;还可以指定任何数量的附加高速缓存。如果您正在使用本地内存高速缓存之外的其他高速缓存后端,或者需要定义多个高速缓存,这就需要添加其他高速缓存项。以下高速缓存选项可用。

BACKEND

Default: '' (Empty string)

The cache backend to use. The built-in cache backends are:

  • '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'

You can use a cache backend that doesn’t ship with Django by setting BACKEND to a fully-qualified path of a cache backend class (i.e. mypackage.backends.whatever.WhateverCache).

KEY_FUNCTION

A string containing a dotted path to a function (or any callable) that defines how to compose a prefix, version and key into a final cache key. The default implementation is equivalent to the function:

def make_key(key, key_prefix, version):
    return ':'.join([key_prefix, str(version), key])

You may use any key function you want, as long as it has the same argument signature.

See the cache documentation for more information.

KEY_PREFIX

Default: '' (Empty string)

A string that will be automatically included (prepended by default) to all cache keys used by the Django server.

See the cache documentation for more information.

LOCATION

默认值:''(空字符串)

要使用的缓存的位置。这可能是文件系统缓存的目录,内存缓存服务器的主机和端口,或者只是本地内存缓存的标识名称。例如:

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

OPTIONS

默认值:无

Extra parameters to pass to the cache backend. Available parameters vary depending on your cache backend.

Some information on available parameters can be found in the Cache Backends documentation. For more information, consult your backend module’s own documentation.

TIMEOUT

默认值:300

高速缓存的有效时间。

New in Django 1.7.

如果此设置的值为,则缓存将不会过期。

VERSION

Default: 1

Django服务器生成的缓存键的默认版本号。

有关详细信息,请参阅缓存文档

CACHE_MIDDLEWARE_ALIAS

Default: default

The cache connection to use for the cache middleware.

CACHE_MIDDLEWARE_KEY_PREFIX

Default: '' (Empty string)

A string which will be prefixed to the cache keys generated by the cache middleware. This prefix is combined with the KEY_PREFIX setting; it does not replace it.

See Django’s cache framework.

CACHE_MIDDLEWARE_SECONDS

Default: 600

The default number of seconds to cache a page for the cache middleware.

See Django’s cache framework.

CSRF_FAILURE_VIEW

Default: 'django.views.csrf.csrf_failure'

A dotted path to the view function to be used when an incoming request is rejected by the CSRF protection. The function should have this signature:

def csrf_failure(request, reason="")

where reason is a short message (intended for developers or logging, not for end users) indicating the reason the request was rejected. See Cross Site Request Forgery protection.

DATABASES

默认:{} (空字典)

一个字典,包含Django 将使用的所有数据库的设置。它是一个嵌套的字典,其内容为数据库别名到包含数据库选项的字典的映射。

DATABASES 设置必须配置一个default 数据库;可以同时指定任何数目的额外数据库。

最简单的配置文件可能是使用SQLite 建立一个数据库。这可以使用以下配置:

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

当连接其他数据库后端,比如MySQL、Oracle 或PostgreSQL,必须提供更多的连接参数。关于如何指定其他的数据库类型,参见后面的ENGINE 设置。下面的例子用于PostgreSQL:

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

下面是更复杂的配置可能需要的选项:

ATOMIC_REQUESTS

默认:False

当需要将每个HTTP 请求封装在一个数据库事务中时,设置它为True参见将事务与HTTP 请求绑定

AUTOCOMMIT

默认:True

如果你需要禁用Django 的事务管理并自己实现,设置它为False

ENGINE

默认:''(空字符串)

使用的数据库后端。内建的数据库后端有:

  • 'django.db.backends.postgresql_psycopg2'
  • 'django.db.backends.mysql'
  • 'django.db.backends.sqlite3'
  • 'django.db.backends.oracle'

你可以不使用Django 自带的数据库后端,通过设置ENGINE 为一个合法的路径即可(例如mypackage.backends.whatever)。

HOST

默认:''(空字符串)

连接数据库时使用哪个主机。空字符串意味着采用localhost 作为主机。 SQLite 不需要这个选项。

如果其值以斜杠('/')开始并且你使用的是MySQL,MySQL 将通过Unix socket 连接。例如:

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

如果你使用的是MySQL 并且该值不是以斜杠开头,那么将假设该值为主机。

如果你使用的是PostgreSQL,默认情况下(空HOST),数据库的连接通过UNIX domain sockets(pg_hba.conf 中的‘local’行)。如果你的UNIX domain socket 不在标准的路径,则使用postgresql.conf 中的unix_socket_directory 值。如果你想通过TCP sockets 连接,请设置HOST 为‘localhost’ 或 ‘127.0.0.1’(pg_hba.conf 中的‘host’行)。在Windows上,你应该始终定义HOST,因为其不可以使用UNIX domain sockets。

NAME

默认:''(空字符串)

使用的数据库名称。对于SQLite,它是数据库文件的完整路径。指定路径时,请始终使用前向的斜杠,即使在Windows 上(例如C:/homes/user/mysite/sqlite3.db)。

CONN_MAX_AGE

默认:0

数据库连接的存活时间,以秒为单位。0 表示在每个请求结束时关闭数据库连接 —— 这是Django 的历史遗留行为,None 表示无限的持久连接。

OPTIONS

默认:{}(空字典)

连接数据库时使用的额外参数。可用的参数与你的数据库后端有关。

数据库后端的文档中可以找到可用的参数的一些信息。更多信息,参考后端模块自身的文档。

PASSWORD

默认:''(空字符串)

连接数据库时使用的密码。SQLite 不需要这个选项。

PORT (端口)

默认:''(空字符串)

连接数据库时使用的端口。空字符串表示默认的端口。SQLite 不需要这个选项。

USER

默认:''(空字符串)

连接数据库时使用的用户名。SQLite 不需要这个选项。

TEST

Changed in Django 1.7:

All TEST sub-entries used to be independent entries in the database settings dictionary, with a TEST_ prefix. For backwards compatibility with older versions of Django, you can define both versions of the settings as long as they match. Further, TEST_CREATE, TEST_USER_CREATE and TEST_PASSWD were changed to CREATE_DB, CREATE_USER and PASSWORD respectively.

Default: {}

用于测试数据库的一个设置字典;有关创建和使用测试数据库的更多详细信息,请参见测试数据库以下条目可用:

CHARSET

Default: None

字符集设置用于指定数据库编码格式。该设置的值会直接传给数据库,所以它的格式是由指定的数据库来决定的。

该字段支持 PostgreSQL (postgresql_psycopg2) 和MySQL (mysql) 数据库。

COLLATION

Default: None

The collation order to use when creating the test database. This value is passed directly to the backend, so its format is backend-specific.

Only supported for the mysql backend (see the MySQL manual for details).

DEPENDENCIES

Default: ['default'], for all databases other than default, which has no dependencies.

The creation-order dependencies of the database. See the documentation on controlling the creation order of test databases for details.

MIRROR

Default: None

The alias of the database that this database should mirror during testing.

This setting exists to allow for testing of primary/replica (referred to as master/slave by some databases) configurations of multiple databases. See the documentation on testing primary/replica configurations for details.

NAME

Default: None

The name of database to use when running the test suite.

If the default value (None) is used with the SQLite database engine, the tests will use a memory resident database. For all other database engines the test database will use the name 'test_' + DATABASE_NAME.

See The test database.

SERIALIZE
New in Django 1.7.1.

Boolean value to control whether or not the default test runner serializes the database into an in-memory JSON string before running tests (used to restore the database state between tests if you don’t have transactions). You can set this to False to speed up creation time if you don’t have any test classes with serialized_rollback=True.

CREATE_DB

Default: True

This is an Oracle-specific setting.

If it is set to False, the test tablespaces won’t be automatically created at the beginning of the tests and dropped at the end.

CREATE_USER

Default: True

这是一个 Oracle-specific 设置.

If it is set to False, the test user won’t be automatically created at the beginning of the tests and dropped at the end.

USER

Default: None

This is an Oracle-specific setting.

The username to use when connecting to the Oracle database that will be used when running tests. If not provided, Django will use 'test_' + USER.

PASSWORD

Default: None

This is an Oracle-specific setting.

The password to use when connecting to the Oracle database that will be used when running tests. If not provided, Django will use a hardcoded default value.

TBLSPACE

Default: None

This is an Oracle-specific setting.

The name of the tablespace that will be used when running tests. If not provided, Django will use 'test_' + USER.

Changed in Django 1.8:

Previously Django used 'test_' + NAME if not provided.

TBLSPACE_TMP

Default: None

This is an Oracle-specific setting.

The name of the temporary tablespace that will be used when running tests. If not provided, Django will use 'test_' + USER + '_temp'.

Changed in Django 1.8:

Previously Django used 'test_' + NAME + '_temp' if not provided.

DATAFILE
New in Django 1.8.

Default: None

This is an Oracle-specific setting.

The name of the datafile to use for the TBLSPACE. If not provided, Django will use TBLSPACE + '.dbf'.

DATAFILE_TMP
New in Django 1.8.

Default: None

This is an Oracle-specific setting.

The name of the datafile to use for the TBLSPACE_TMP. If not provided, Django will use TBLSPACE_TMP + '.dbf'.

DATAFILE_MAXSIZE
New in Django 1.8.

Default: '500M'

Changed in Django 1.8:

The previous value was 200M and was not user customizable.

This is an Oracle-specific setting.

The maximum size that the DATAFILE is allowed to grow to.

DATAFILE_TMP_MAXSIZE
New in Django 1.8.

Default: '500M'

Changed in Django 1.8:

The previous value was 200M and was not user customizable.

This is an Oracle-specific setting.

The maximum size that the DATAFILE_TMP is allowed to grow to.

TEST_CHARSET

Deprecated since version 1.7: Use the CHARSET entry in the TEST dictionary.

TEST_COLLATION

Deprecated since version 1.7: Use the COLLATION entry in the TEST dictionary.

TEST_DEPENDENCIES

Deprecated since version 1.7: Use the DEPENDENCIES entry in the TEST dictionary.

TEST_MIRROR

Deprecated since version 1.7: Use the MIRROR entry in the TEST dictionary.

TEST_NAME

Deprecated since version 1.7: Use the NAME entry in the TEST dictionary.

TEST_CREATE

Deprecated since version 1.7: Use the CREATE_DB entry in the TEST dictionary.

TEST_USER

Deprecated since version 1.7: Use the USER entry in the TEST dictionary.

TEST_USER_CREATE

Deprecated since version 1.7: Use the CREATE_USER entry in the TEST dictionary.

TEST_PASSWD

Deprecated since version 1.7: Use the PASSWORD entry in the TEST dictionary.

TEST_TBLSPACE

Deprecated since version 1.7: Use the TBLSPACE entry in the TEST dictionary.

TEST_TBLSPACE_TMP

Deprecated since version 1.7: Use the TBLSPACE_TMP entry in the TEST dictionary.

DATABASE_ROUTERS

Default: [] (Empty list)

The list of routers that will be used to determine which database to use when performing a database queries.

See the documentation on automatic database routing in multi database configurations.

DATE_FORMAT

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

The default formatting to use for displaying date fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings.

See also DATETIME_FORMAT, TIME_FORMAT and SHORT_DATE_FORMAT.

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 tuple of formats that will be accepted when inputting data on a date field. Formats will be tried in order, using the first valid one. Note that these format strings use Python’s datetime module syntax, not the format strings from the date Django template tag.

When USE_L10N is True, the locale-dictated format has higher precedence and will be applied instead.

See also DATETIME_INPUT_FORMATS and TIME_INPUT_FORMATS.

DATETIME_FORMAT

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

The default formatting to use for displaying datetime fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings.

See also DATE_FORMAT, TIME_FORMAT and SHORT_DATETIME_FORMAT.

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 tuple of formats that will be accepted when inputting data on a datetime field. Formats will be tried in order, using the first valid one. Note that these format strings use Python’s datetime module syntax, not the format strings from the date Django template tag.

When USE_L10N is True, the locale-dictated format has higher precedence and will be applied instead.

See also DATE_INPUT_FORMATS and TIME_INPUT_FORMATS.

DEBUG

Default: False

打开/关闭调试模式的布尔值。

部署网站的时候不要把DEBUG 打开.

你明白了吗?部署网站的时候一定不要把 DEBUG 打开.

调试模式的一个重要特性是显示错误页面的细节。DEBUGTrue的时候,若你的应用产生了一个异常,Django 会显示追溯细节,包括许多环境变量的元数据, 比如所有当前定义的Django设置(在settings.py中的).

作为安全措施, Django 将 不会 包括敏感的 (或者可能会被攻击的)设置, 例如 SECRET_KEY. 特别是名字中包含下面这些单词的设置:

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

注意,这里使用的是 部分 匹配. 'PASS'将匹配 PASSWORD, 另外 'TOKEN' 也将匹配 TOKENIZED 等等.

不过,总有一些调试的输出你不希望展现给公众的。文件路径, 配置信息和其他,将会提供信息给攻击者来攻击你的服务器。

另外,很重要的是要记住当你运行时 DEBUG 模式打开的话, Django 记住所有执行的 SQL 查询语句。 这在进行 DEBUG 调试时非常有用, 但这会消耗运行服务器的大量内存资源.

最后,如果DEBUGFalse,你还需要正确设置ALLOWED_HOSTS设置错误将导致对所有的请求返回“Bad Request (400)”。

DEBUG_PROPAGATE_EXCEPTIONS

Default: False

If set to True, Django’s normal exception handling of view functions will be suppressed, and exceptions will propagate upwards. This can be useful for some test setups, and should never be used on a live site.

DECIMAL_SEPARATOR

Default: '.' (Dot)

Default decimal separator used when formatting decimal numbers.

Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead.

See also NUMBER_GROUPING, THOUSAND_SEPARATOR and USE_THOUSAND_SEPARATOR.

DEFAULT_CHARSET

Default: 'utf-8'

Default charset to use for all HttpResponse objects, if a MIME type isn’t manually specified. Used with DEFAULT_CONTENT_TYPE to construct the Content-Type header.

DEFAULT_CONTENT_TYPE

Default: 'text/html'

Default content type to use for all HttpResponse objects, if a MIME type isn’t manually specified. Used with DEFAULT_CHARSET to construct the Content-Type header.

DEFAULT_EXCEPTION_REPORTER_FILTER

Default: django.views.debug.SafeExceptionReporterFilter

Default exception reporter filter class to be used if none has been assigned to the HttpRequest instance yet. See Filtering error reports.

DEFAULT_FILE_STORAGE

默认:django.core.files.storage.FileSystemStorage

默认的Storage 类,用于没有指定文件系统的任何和文件相关的操作。参见管理文件

DEFAULT_FROM_EMAIL

Default: 'webmaster@localhost'

用于来自站点管理员的各种自动通信的默认电子邮件地址。这不包括发送到ADMINSMANAGERS的错误消息;有关详细信息,请参阅SERVER_EMAIL

DEFAULT_INDEX_TABLESPACE

Default: '' (Empty string)

Default tablespace to use for indexes on fields that don’t specify one, if the backend supports it (see Tablespaces).

DEFAULT_TABLESPACE

Default: '' (Empty string)

Default tablespace to use for models that don’t specify one, if the backend supports it (see Tablespaces).

DISALLOWED_USER_AGENTS

Default: () (Empty tuple)

List of compiled regular expression objects representing User-Agent strings that are not allowed to visit any page, systemwide. Use this for bad robots/crawlers. This is only used if CommonMiddleware is installed (see Middleware).

EMAIL_BACKEND

默认:'django.core.mail.backends.smtp.EmailBackend'

用于发送邮件的后端。可选的后端参见发送邮件

EMAIL_FILE_PATH

默认:未指定

file 类型的邮件后端保存输出文件时使用的目录。

EMAIL_HOST

默认:'localhost'

发送邮件使用的主机。

另见EMAIL_PORT

EMAIL_HOST_PASSWORD

默认:''(空字符串)

EMAIL_HOST 定义的SMTP 服务器使用的密码。这个设置与EMAIL_HOST_USER 一起用于SMTP 服务器的认证。如果两个中有一个为空,Django 则不会尝试认证。

另见EMAIL_HOST_USER

EMAIL_HOST_USER

默认:''(空字符串)

EMAIL_HOST 定义的SMTP 服务器使用的用户名。如果为空,Django 不会尝试认证。

另见EMAIL_HOST_PASSWORD

EMAIL_PORT

默认:25

EMAIL_HOST 定义的SMTP 服务器使用的端口。

EMAIL_SUBJECT_PREFIX

Default: '[Django] '

Subject-line prefix for email messages sent with django.core.mail.mail_admins or django.core.mail.mail_managers. You’ll probably want to include the trailing space.

EMAIL_USE_TLS

Default: False

是否使用TLS(安全)当与SMTP服务器的连接。这是用于显式TLS连接,通常在端口587上。如果你正在经历挂连接,看到隐EMAIL_USE_SSL TLS设置。This is used for explicit TLS connections, generally on port 587. If you are experiencing hanging connections, see the implicit TLS setting EMAIL_USE_SSL.

EMAIL_USE_SSL

New in Django 1.7.

Default: False

Whether to use an implicit TLS (secure) connection when talking to the SMTP server. In most email documentation this type of TLS connection is referred to as SSL. It is generally used on port 465. If you are experiencing problems, see the explicit TLS setting EMAIL_USE_TLS.

Note that EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set one of those settings to True.

EMAIL_SSL_CERTFILE

New in Django 1.8.

Default: None

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

EMAIL_SSL_KEYFILE

New in Django 1.8.

Default: None

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

Note that setting EMAIL_SSL_CERTFILE and EMAIL_SSL_KEYFILE doesn’t result in any certificate checking. They’re passed to the underlying SSL connection. Please refer to the documentation of Python’s ssl.wrap_socket() function for details on how the certificate chain file and private key file are handled.

EMAIL_TIMEOUT

New in Django 1.8.

Default: None

Specifies a timeout in seconds for blocking operations like the connection attempt.

FILE_CHARSET

Default: 'utf-8'

The character encoding used to decode any files read from disk. This includes template files and initial SQL data files.

FILE_UPLOAD_HANDLERS

Default:

("django.core.files.uploadhandler.MemoryFileUploadHandler",
 "django.core.files.uploadhandler.TemporaryFileUploadHandler")

A tuple of handlers to use for uploading. Changing this setting allows complete customization – even replacement – of Django’s upload process.

See Managing files for details.

FILE_UPLOAD_MAX_MEMORY_SIZE

Default: 2621440 (i.e. 2.5 MB).

The maximum size (in bytes) that an upload will be before it gets streamed to the file system. See Managing files for details.

FILE_UPLOAD_DIRECTORY_PERMISSIONS

New in Django 1.7.

Default: None

The numeric mode to apply to directories created in the process of uploading files.

This setting also determines the default permissions for collected static directories when using the collectstatic management command. See collectstatic for details on overriding it.

This value mirrors the functionality and caveats of the FILE_UPLOAD_PERMISSIONS setting.

FILE_UPLOAD_PERMISSIONS

Default: None

The numeric mode (i.e. 0o644) to set newly uploaded files to. For more information about what these modes mean, see the documentation for os.chmod().

If this isn’t given or is None, you’ll get operating-system dependent behavior. On most platforms, temporary files will have a mode of 0o600, and files saved from memory will be saved using the system’s standard umask.

For security reasons, these permissions aren’t applied to the temporary files that are stored in FILE_UPLOAD_TEMP_DIR.

This setting also determines the default permissions for collected static files when using the collectstatic management command. See collectstatic for details on overriding it.

Warning

Always prefix the mode with a 0.

If you’re not familiar with file modes, please note that the leading 0 is very important: it indicates an octal number, which is the way that modes must be specified. If you try to use 644, you’ll get totally incorrect behavior.

FILE_UPLOAD_TEMP_DIR

Default: None

The directory to store data (typically files larger than FILE_UPLOAD_MAX_MEMORY_SIZE) temporarily while uploading files. If None, Django will use the standard temporary directory for the operating system. 例如,在linux风格的操作系统上,这将默认为/tmp

See Managing files for details.

FIRST_DAY_OF_WEEK

Default: 0 (Sunday)

Number representing the first day of the week. This is especially useful when displaying a calendar. This value is only used when not using format internationalization, or when a format cannot be found for the current locale.

The value must be an integer from 0 to 6, where 0 means Sunday, 1 means Monday and so on.

FIXTURE_DIRS

Default: () (Empty tuple)

List of directories searched for fixture files, in addition to the fixtures directory of each application, in search order.

Note that these paths should use Unix-style forward slashes, even on Windows.

See Providing initial data with fixtures and Fixture loading.

FORCE_SCRIPT_NAME

默认值: None

如果不是None,这将用作任何HTTP请求中SCRIPT_NAME环境变量的值。此设置可用于覆盖服务器提供的SCRIPT_NAME值,该值可能是首选值的重写版本,或者根本不提供。

FORMAT_MODULE_PATH

Default: None

A full Python path to a Python package that contains format definitions for project locales. If not None, Django will check for a formats.py file, under the directory named as the current locale, and will use the formats defined on this file.

For example, if FORMAT_MODULE_PATH is set to mysite.formats, and current language is en (English), Django will expect a directory tree like:

mysite/
    formats/
        __init__.py
        en/
            __init__.py
            formats.py
Changed in Django 1.8:

You can also set this setting to a list of Python paths, for example:

FORMAT_MODULE_PATH = [
    'mysite.formats',
    'some_app.formats',
]

When Django searches for a certain format, it will go through all given Python paths until it finds a module that actually defines the given format. This means that formats defined in packages farther up in the list will take precedence over the same formats in packages farther down.

Available formats are DATE_FORMAT, TIME_FORMAT, DATETIME_FORMAT, YEAR_MONTH_FORMAT, MONTH_DAY_FORMAT, SHORT_DATE_FORMAT, SHORT_DATETIME_FORMAT, FIRST_DAY_OF_WEEK, DECIMAL_SEPARATOR, THOUSAND_SEPARATOR and NUMBER_GROUPING.

IGNORABLE_404_URLS

Default: ()

List of compiled regular expression objects describing URLs that should be ignored when reporting HTTP 404 errors via email (see Error reporting). Regular expressions are matched against request's full paths (including query string, if any). Use this if your site does not provide a commonly requested file such as favicon.ico or robots.txt, or if it gets hammered by script kiddies.

This is only used if BrokenLinkEmailsMiddleware is enabled (see Middleware).

INSTALLED_APPS

Default: () (Empty tuple)

一个字符串元组,它标明了所有能在django安装的应用Each string should be a dotted Python path to:

  • an application configuration class, or
  • a package containing a application.

Learn more about application configurations.

Changed in Django 1.7:

INSTALLED_APPS now supports application configurations.

使用应用程序注册表进行自我检查

您的代码不应直接访问INSTALLED_APPS请改用django.apps.apps

应用程序名称和标签在INSTALLED_APPS中必须是唯一的

Application names — the dotted Python path to the application package — must be unique. 没有办法包含相同的应用程序两次,没有重复其代码在另一个名称下。

应用程序标签 - 默认情况下,名称的最后一部分也必须是唯一的。例如,您不能同时包含django.contrib.authmyproject.auth但是,您可以使用定义不同标签的自定义配置重新标记应用程序。

无论INSTALLED_APPS是否引用应用程序包上的应用程序配置类,这些规则都适用。

当多个应用程序提供相同资源(模板,静态文件,管理命令,翻译)的不同版本时,INSTALLED_APPS中首先列出的应用程序优先。

INTERNAL_IPS

Default: () (Empty tuple)

A tuple of IP addresses, as strings, that:

LANGUAGE_CODE

Default: 'en-us'

A string representing the language code for this installation. This should be in standard language ID format. For example, U.S. English is "en-us". See also the list of language identifiers and Internationalization and localization.

USE_I18N must be active for this setting to have any effect.

It serves two purposes:

  • If the locale middleware isn’t in use, it decides which translation is served to all users.
  • If the locale middleware is active, it provides a fallback language in case the user’s preferred language can’t be determined or is not supported by the Web site. It also provides the fallback translation when a translation for a given literal doesn’t exist for the user’s preferred language.
Changed in Django 1.8:

The fallback for translation literals was added.

See How Django discovers language preference for more details.

LANGUAGES

Default: A tuple of all available languages. This list is continually growing and including a copy here would inevitably become rapidly out of date. You can see the current list of translated languages by looking in django/conf/global_settings.py (or view the online source).

The list is a tuple of two-tuples in the format (language code, language name) – for example, ('ja', 'Japanese'). This specifies which languages are available for language selection. See Internationalization and localization.

Generally, the default value should suffice. Only set this setting if you want to restrict language selection to a subset of the Django-provided languages.

If you define a custom LANGUAGES setting, you can mark the language names as translation strings using the ugettext_lazy() function.

Here’s a sample settings file:

from django.utils.translation import ugettext_lazy as _

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

LOCALE_PATHS

Default: () (Empty tuple)

A tuple of directories where Django looks for translation files. See How Django discovers translations.

Example:

LOCALE_PATHS = (
    '/home/www/project/common_files/locale',
    '/var/local/translations/locale',
)

Django will look within each of these paths for the <locale_code>/LC_MESSAGES directories containing the actual translation files.

LOGGING

Default: A logging configuration dictionary.

A data structure containing configuration information. The contents of this data structure will be passed as the argument to the configuration method described in LOGGING_CONFIG.

Among other things, the default logging configuration passes HTTP 500 server errors to an email log handler when DEBUG is False. See also Configuring logging.

You can see the default logging configuration by looking in django/utils/log.py (or view the online source).

LOGGING_CONFIG

Default: 'logging.config.dictConfig'

A path to a callable that will be used to configure logging in the Django project. Points at a instance of Python’s dictConfig configuration method by default.

If you set LOGGING_CONFIG to None, the logging configuration process will be skipped.

Changed in Django 1.7:

Previously, the default value was 'django.utils.log.dictConfig'.

MANAGERS

Default: () (Empty tuple)

一个有 ADMINS相同格式的元组, 它指定了谁应该得到 broken link notifications 当BrokenLinkEmailsMiddleware 启用的时候.

MEDIA_ROOT

缺省: '' (空字符串)

指向存放用户上传文件所在目录的文件系统绝对路径。

例如: "/var/www/example.com/media/"

参见MEDIA_URL.

警告:

MEDIA_ROOTSTATIC_ROOT 必须设置为不同的值。在引入(设置)STATIC_ROOT 之前,  静态文件的处理将依赖MEDIA_ROOT但是,由于这样做会导致产生隐藏的严重安全问题,所以必须进行有效的安全检查以避免这种情况发生。

MEDIA_URL

缺省: '' (空字符串)

MEDIA_URL指向MEDIA_ROOT所指定的media文件,通过这个地址来管理所存储文件该URL设置为非空值时,必须以斜杠“/”结束。你需要 配置这些文件用于 开发环境或线上环境。.

若你打算在模版中使用 {{ MEDIA_URL }} , 那么应在TEMPLATES'context_processors'设置中添加'django.template.context_processors.media'.

例如: "http://media.example.com/"

警告

如果接受非授信用户上传的内容,将会给系统带来安全风险。关于迁移细节,请参见用户上传内容中安全指南一节。

警告

MEDIA_URLSTATIC_URL 必须设置为不同的值。更多细节,请参见 MEDIA_ROOT

MIDDLEWARE_CLASSES

Default:

('django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware')

使用中间件类的元组 See Middleware.

Changed in Django 1.7:

SessionMiddleware, AuthenticationMiddleware, and MessageMiddleware were removed from this setting.

MIGRATION_MODULES

Default:

{}  # empty dictionary

A dictionary specifying the package where migration modules can be found on a per-app basis. The default value of this setting is an empty dictionary, but the default package name for migration modules is migrations.

Example:

{'blog': 'blog.db_migrations'}

In this case, migrations pertaining to the blog app will be contained in the blog.db_migrations package.

If you provide the app_label argument, makemigrations will automatically create the package if it doesn’t already exist.

MONTH_DAY_FORMAT

Default: 'F j'

The default formatting to use for date fields on Django admin change-list pages – and, possibly, by other parts of the system – in cases when only the month and day are displayed.

For example, when a Django admin change-list page is being filtered by a date drilldown, the header for a given day displays the day and month. Different locales have different formats. For example, U.S. English would say “January 1,” whereas Spanish might say “1 Enero.”

Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied.

See allowed date format strings. See also DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT and YEAR_MONTH_FORMAT.

NUMBER_GROUPING

Default: 0

Number of digits grouped together on the integer part of a number.

Common use is to display a thousand separator. If this setting is 0, then no grouping will be applied to the number. If this setting is greater than 0, then THOUSAND_SEPARATOR will be used as the separator between those groups.

Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead.

See also DECIMAL_SEPARATOR, THOUSAND_SEPARATOR and USE_THOUSAND_SEPARATOR.

PREPEND_WWW

Default: False

Whether to prepend the “www.” subdomain to URLs that don’t have it. This is only used if CommonMiddleware is installed (see Middleware). See also APPEND_SLASH.

ROOT_URLCONF

默认值:没有定义

一个字符串,表示根URLconf 的完整Python 导入路径。例如:"mydjangoapps.urls"每个请求可以覆盖它,方法是设置进来的HttpRequest 对象的urlconf属性。细节参见Django 如何处理一个请求

SECRET_KEY

Default: '' (Empty string)

A secret key for a particular Django installation. This is used to provide cryptographic signing, and should be set to a unique, unpredictable value.

django-admin startproject automatically adds a randomly-generated SECRET_KEY to each new project.

Django will refuse to start if SECRET_KEY is not set.

Warning

Keep this value secret.

Running Django with a known SECRET_KEY defeats many of Django’s security protections, and can lead to privilege escalation and remote code execution vulnerabilities.

The secret key is used for:

如果您更换密钥,上述所有内容都将失效。Secret keys are not used for passwords of users and key rotation will not affect them.

SECURE_BROWSER_XSS_FILTER

New in Django 1.8.

Default: False

If True, the SecurityMiddleware sets the X-XSS-Protection: 1; mode=block header on all responses that do not already have it.

SECURE_CONTENT_TYPE_NOSNIFF

New in Django 1.8.

Default: False

If True, the SecurityMiddleware sets the X-Content-Type-Options: nosniff header on all responses that do not already have it.

SECURE_HSTS_INCLUDE_SUBDOMAINS

New in Django 1.8.

Default: False

If True, the SecurityMiddleware adds the includeSubDomains tag to the HTTP Strict Transport Security header. It has no effect unless SECURE_HSTS_SECONDS is set to a non-zero value.

Warning

Setting this incorrectly can irreversibly (for some time) break your site. Read the HTTP Strict Transport Security documentation first.

SECURE_HSTS_SECONDS

New in Django 1.8.

Default: 0

If set to a non-zero integer value, the SecurityMiddleware sets the HTTP Strict Transport Security header on all responses that do not already have it.

Warning

Setting this incorrectly can irreversibly (for some time) break your site. Read the HTTP Strict Transport Security documentation first.

SECURE_PROXY_SSL_HEADER

Default: None

A tuple representing a HTTP header/value combination that signifies a request is secure. This controls the behavior of the request object’s is_secure() method.

This takes some explanation. By default, is_secure() is able to determine whether a request is secure by looking at whether the requested URL uses “https://”. This is important for Django’s CSRF protection, and may be used by your own code or third-party apps.

If your Django app is behind a proxy, though, the proxy may be “swallowing” the fact that a request is HTTPS, using a non-HTTPS connection between the proxy and Django. In this case, is_secure() would always return False – even for requests that were made via HTTPS by the end user.

In this situation, you’ll want to configure your proxy to set a custom HTTP header that tells Django whether the request came in via HTTPS, and you’ll want to set SECURE_PROXY_SSL_HEADER so that Django knows what header to look for.

You’ll need to set a tuple with two elements – the name of the header to look for and the required value. For example:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

Here, we’re telling Django that we trust the X-Forwarded-Proto header that comes from our proxy, and any time its value is 'https', then the request is guaranteed to be secure (i.e., it originally came in via HTTPS). Obviously, you should only set this setting if you control your proxy or have some other guarantee that it sets/strips this header appropriately.

Note that the header needs to be in the format as used by request.META – all caps and likely starting with HTTP_. (Remember, Django automatically adds 'HTTP_' to the start of x-header names before making the header available in request.META.)

Warning

You will probably open security holes in your site if you set this without knowing what you’re doing. And if you fail to set it when you should. Seriously.

Make sure ALL of the following are true before setting this (assuming the values from the example above):

  • Your Django app is behind a proxy.
  • Your proxy strips the X-Forwarded-Proto header from all incoming requests. In other words, if end users include that header in their requests, the proxy will discard it.
  • Your proxy sets the X-Forwarded-Proto header and sends it to Django, but only for requests that originally come in via HTTPS.

If any of those are not true, you should keep this setting set to None and find another way of determining HTTPS, perhaps via custom middleware.

SECURE_REDIRECT_EXEMPT

New in Django 1.8.

Default: []

If a URL path matches a regular expression in this list, the request will not be redirected to HTTPS. If SECURE_SSL_REDIRECT is False, this setting has no effect.

SECURE_SSL_HOST

New in Django 1.8.

Default: None

如果字符串(例如secure.example.com),所有SSL重定向将被定向到此主机,而不是原始请求的主机(例如www.example.com) 。如果SECURE_SSL_REDIRECTFalse,则此设置无效。

SECURE_SSL_REDIRECT

New in Django 1.8.

Default: False.

If True, the SecurityMiddleware redirects all non-HTTPS requests to HTTPS (except for those URLs matching a regular expression listed in SECURE_REDIRECT_EXEMPT).

Note

If turning this to True causes infinite redirects, it probably means your site is running behind a proxy and can’t tell which requests are secure and which are not. Your proxy likely sets a header to indicate secure requests; you can correct the problem by finding out what that header is and configuring the SECURE_PROXY_SSL_HEADER setting accordingly.

SERIALIZATION_MODULES

Default: Not defined.

A dictionary of modules containing serializer definitions (provided as strings), keyed by a string identifier for that serialization type. For example, to define a YAML serializer, use:

SERIALIZATION_MODULES = {'yaml': 'path.to.yaml_serializer'}

SERVER_EMAIL

Default: 'root@localhost'

The email address that error messages come from, such as those sent to ADMINS and MANAGERS.

Why are my emails sent from a different address?

This address is used only for error messages. It is not the address that regular email messages sent with send_mail() come from; for that, see DEFAULT_FROM_EMAIL.

SHORT_DATE_FORMAT

Default: m/d/Y (e.g. 12/31/2003)

An available formatting that can be used for displaying date fields on templates. Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied. See allowed date format strings.

See also DATE_FORMAT and SHORT_DATETIME_FORMAT.

SHORT_DATETIME_FORMAT

Default: m/d/Y P (e.g. 12/31/2003 4 p.m.)

An available formatting that can be used for displaying datetime fields on templates. Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied. See allowed date format strings.

See also DATE_FORMAT and SHORT_DATE_FORMAT.

SIGNING_BACKEND

Default: 'django.core.signing.TimestampSigner'

The backend used for signing cookies and other data.

See also the Cryptographic signing documentation.

SILENCED_SYSTEM_CHECKS

New in Django 1.7.

Default: []

A list of identifiers of messages generated by the system check framework (i.e. ["models.W001"]) that you wish to permanently acknowledge and ignore. Silenced warnings will no longer be output to the console; silenced errors will still be printed, but will not prevent management commands from running.

See also the System check framework documentation.

TEMPLATES

New in Django 1.8.

Default:: [] (Empty list)

Django的模板使用一个列表来进行配置。列表中每一项都是一个字典类型数据,可以配置模板不同的功能。

这里有一个简单的设置,告诉Django模板引擎从已安装的应用程序中的模板子目录加载模板:

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

The following options are available for all backends.

BACKEND

Default: not defined

The template backend to use. The built-in template backends are:

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

You can use a template backend that doesn’t ship with Django by setting BACKEND to a fully-qualified path (i.e. 'mypackage.whatever.Backend').

NAME

Default: see below

The alias for this particular template engine. It’s an identifier that allows selecting an engine for rendering. Aliases must be unique across all configured template engines.

It defaults to the name of the module defining the engine class, i.e. the next to last piece of BACKEND, when it isn’t provided. For example if the backend is 'mypackage.whatever.Backend' then its default name is 'whatever'.

DIRS

默认设置: [] (空列表)

包含搜索顺序的序列,搜索引擎会按照这个顺序查找template资源文件

APP_DIRS

Default:: False

Templates引擎是否应该在已安装的app中查找Template源文件

OPTIONS

Default:: {} (Empty dict)

Extra parameters to pass to the template backend. Available parameters vary depending on the template backend.

TEMPLATE_CONTEXT_PROCESSORS

Default:

("django.contrib.auth.context_processors.auth",
"django.template.context_processors.debug",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages")

Deprecated since version 1.8: Set the 'context_processors' option in the OPTIONS of a DjangoTemplates backend instead.

A tuple of callables that are used to populate the context in RequestContext. These callables take a request object as their argument and return a dictionary of items to be merged into the context.

Changed in Django 1.8:

Built-in template context processors were moved from django.core.context_processors to django.template.context_processors in Django 1.8.

TEMPLATE_DEBUG

Default: False

Deprecated since version 1.8: Set the 'debug' option in the OPTIONS of a DjangoTemplates backend instead.

A boolean that turns on/off template debug mode. If this is True, the fancy error page will display a detailed report for any exception raised during template rendering. This report contains the relevant snippet of the template, with the appropriate line highlighted.

Note that Django only displays fancy error pages if DEBUG is True, so you’ll want to set that to take advantage of this setting.

See also DEBUG.

TEMPLATE_DIRS

Default: () (Empty tuple)

Deprecated since version 1.8: Set the DIRS option of a DjangoTemplates backend instead.

List of locations of the template source files searched by django.template.loaders.filesystem.Loader, in search order.

Note that these paths should use Unix-style forward slashes, even on Windows.

See The Django template language.

TEMPLATE_LOADERS

Default:

('django.template.loaders.filesystem.Loader',
 'django.template.loaders.app_directories.Loader')

Deprecated since version 1.8: Set the 'loaders' option in the OPTIONS of a DjangoTemplates backend instead.

A tuple of template loader classes, specified as strings. Each Loader class knows how to import templates from a particular source. Optionally, a tuple can be used instead of a string. The first item in the tuple should be the Loader’s module, subsequent items are passed to the Loader during initialization. See The Django template language: for Python programmers.

TEMPLATE_STRING_IF_INVALID

Default: '' (Empty string)

Deprecated since version 1.8: Set the 'string_if_invalid' option in the OPTIONS of a DjangoTemplates backend instead.

Output, as a string, that the template system should use for invalid (e.g. misspelled) variables. See How invalid variables are handled.

TEST_RUNNER

Default: 'django.test.runner.DiscoverRunner'

The name of the class to use for starting the test suite. See Using different testing frameworks.

TEST_NON_SERIALIZED_APPS

New in Django 1.7.

Default: []

In order to restore the database state between tests for TransactionTestCases and database backends without transactions, Django will serialize the contents of all apps with migrations when it starts the test run so it can then reload from that copy before tests that need it.

This slows down the startup time of the test runner; if you have apps that you know don’t need this feature, you can add their full names in here (e.g. 'django.contrib.contenttypes') to exclude them from this serialization process.

THOUSAND_SEPARATOR

Default: , (Comma)

Default thousand separator used when formatting numbers. This setting is used only when USE_THOUSAND_SEPARATOR is True and NUMBER_GROUPING is greater than 0.

Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead.

See also NUMBER_GROUPING, DECIMAL_SEPARATOR and USE_THOUSAND_SEPARATOR.

TIME_FORMAT

Default: 'P' (e.g. 4 p.m.)

The default formatting to use for displaying time fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings.

See also DATE_FORMAT and DATETIME_FORMAT.

TIME_INPUT_FORMATS

Default:

(
    '%H:%M:%S',     # '14:30:59'
    '%H:%M:%S.%f',  # '14:30:59.000200'
    '%H:%M',        # '14:30'
)

A tuple of formats that will be accepted when inputting data on a time field. Formats will be tried in order, using the first valid one. Note that these format strings use Python’s datetime module syntax, not the format strings from the date Django template tag.

When USE_L10N is True, the locale-dictated format has higher precedence and will be applied instead.

See also DATE_INPUT_FORMATS and DATETIME_INPUT_FORMATS.

TIME_ZONE

默认:'America/Chicago'

一个字符串或者None,表示项目的时区。参见时区列表

因为Django 第一次发布时,TIME_ZONE 设置为 'America/Chicago',为了向前兼容,全局设置( 在你的项目的settings.py 中没有定义任何内容时使用)仍然保留为'America/Chicago'新的项目模板默认为'UTC'

注意,它不一定要和服务器的时区一致。例如,一个服务器可上可能有多个Django 站点,每个站点都有一个单独的时区设置。

USE_TZFalse 时,它将成为Django 存储所有日期和时间时使用的时区。USE_TZTrue 时,它是Django 显示模板中以及解释表单中的日期和时间默认使用的时区。

Django 设置os.environ['TZ'] 变量为你在TIME_ZONE 设置中指定的时区。所以,你的所有视图和模型都将自动在这个时区中运作。然而,在下面这些情况下,Django 不会设置TZ 环境变量:

  • 如果你使用手工配置选项,参见手工配置设置,或
  • 如果你指定TIME_ZONE = None这将导致Django 使用系统的时区。然而,当USE_TZ = True 时不鼓励这样做,因为这使得本地时间和UTC 之间的转换不太可靠。

如果Django 没有设置TZ 环境变量,那么你需要自己确保你的进程在正确的环境中运行。

在Windows 环境中,Django 不能可靠地交替其它时区。如果你在Windows 上运行Django,TIME_ZONE 必须设置为与系统时区一致。

USE_ETAGS

Default: False

这是一个布尔变量,它指定是否产生"Etag"头,这种方式会节省带宽但是会降低性能,这个标签在 CommonMiddleware (see Middleware) 和``Cache Framework`` 中使用(详情见Django’s cache framework).

USE_I18N

Default: True

这是一个布尔值,它指定Django的翻译系统是否被启用。它提供了一种简单的方式去关闭翻译系统。如果设置为 False, Django 会做一些优化,不去加载翻译机制

See also LANGUAGE_CODE, USE_L10N and USE_TZ.

USE_L10N

Default: False

是一个布尔值,用于决定是否默认进行日期格式本地化。If this is set to True, e.g. Django will display numbers and dates using the format of the current locale.

See also LANGUAGE_CODE, USE_I18N and USE_TZ.

Note

The default settings.py file created by django-admin startproject includes USE_L10N = True for convenience.

USE_THOUSAND_SEPARATOR

Default: False

A boolean that specifies whether to display numbers using a thousand separator. When USE_L10N is set to True and if this is also set to True, Django will use the values of THOUSAND_SEPARATOR and NUMBER_GROUPING to format numbers.

See also DECIMAL_SEPARATOR, NUMBER_GROUPING and THOUSAND_SEPARATOR.

USE_TZ

默认: False

这是一个布尔值,用来指定是否使用指定的时区(TIME_ZONE)的时间.若为 True, 则Django 会使用内建的时区的时间否则, Django 将会使用本地的时间

See also TIME_ZONE, USE_I18N and USE_L10N.

注意

使用django-admin startproject创建的项目中的 settings.py 文件中, 为了方便将 USE_TZ 设置为 True

USE_X_FORWARDED_HOST

Default: False

A boolean that specifies whether to use the X-Forwarded-Host header in preference to the Host header. This should only be enabled if a proxy which sets this header is in use.

WSGI_APPLICATION

Default: None

The full Python path of the WSGI application object that Django’s built-in servers (e.g. runserver) will use. The django-admin startproject management command will create a simple wsgi.py file with an application callable in it, and point this setting to that application.

If not set, the return value of django.core.wsgi.get_wsgi_application() will be used. In this case, the behavior of runserver will be identical to previous Django versions.

YEAR_MONTH_FORMAT

Default: 'F Y'

The default formatting to use for date fields on Django admin change-list pages – and, possibly, by other parts of the system – in cases when only the year and month are displayed.

For example, when a Django admin change-list page is being filtered by a date drilldown, the header for a given month displays the month and the year. Different locales have different formats. For example, U.S. English would say “January 2006,” whereas another locale might say “2006/January.”

Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied.

See allowed date format strings. See also DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT and MONTH_DAY_FORMAT.

X_FRAME_OPTIONS

Default: 'SAMEORIGIN'

The default value for the X-Frame-Options header used by XFrameOptionsMiddleware. See the clickjacking protection documentation.

Auth

用于django.contrib.auth 的设置。

AUTHENTICATION_BACKENDS

默认:('django.contrib.auth.backends.ModelBackend',)

一个元组,包含认证后台的类(字符串形式),用于认证用户。详细信息参见认证后台的文档

AUTH_USER_MODEL

默认:‘auth.User’

表示用户的模型。参见自定义用户模型

警告

You cannot change the AUTH_USER_MODEL setting during the lifetime of a project (i.e. once you have made and migrated models that depend on it) without serious effort. It is intended to be set at the project start, and the model it refers to must be available in the first migration of the app that it lives in. See Substituting a custom User model for more details.

LOGIN_REDIRECT_URL

默认:'/accounts/profile/'

登录之后,contrib.auth.login 视图找不到next 参数时,请求被重定向到的URL。

例如,它被login_required() 装饰器使用。

这个设置还接收视图函数名称和命名的URL 模式,它可以减少重复的配置,因为这样你就不需要在两个地方定义该URL(settings 和URLconf)。

LOGIN_URL

默认:'/accounts/login/'

登录的URL,特别是使用login_required() 装饰器的时候。

这个设置还接收视图函数名称和命名的URL 模式,它可以减少重复的配置,因为这样你就不需要在两个地方定义该URL(settings 和URLconf)。

LOGOUT_URL

默认:'/accounts/logout/'

与LOGIN_URL 配对。

PASSWORD_RESET_TIMEOUT_DAYS

默认:3

重置密码的链接有效的天数。用于django.contrib.auth 的重置密码功能。

PASSWORD_HASHERS

参见Django 如何存储密码

默认:

('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

Settings for django.contrib.messages.

MESSAGE_LEVEL

Default: messages.INFO

Sets the minimum message level that will be recorded by the messages framework. See message levels for more details.

Important

If you override MESSAGE_LEVEL in your settings file and rely on any of the built-in constants, you must import the constants module directly to avoid the potential for circular imports, e.g.:

from django.contrib.messages import constants as message_constants
MESSAGE_LEVEL = message_constants.DEBUG

If desired, you may specify the numeric values for the constants directly according to the values in the above constants table.

MESSAGE_STORAGE

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

Controls where Django stores message data. Valid values are:

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

See message storage backends for more details.

The backends that use cookies – CookieStorage and FallbackStorage – use the value of SESSION_COOKIE_DOMAIN, SESSION_COOKIE_SECURE and SESSION_COOKIE_HTTPONLY when setting their cookies.

MESSAGE_TAGS

Default:

{messages.DEBUG: 'debug',
messages.INFO: 'info',
messages.SUCCESS: 'success',
messages.WARNING: 'warning',
messages.ERROR: 'error'}

This sets the mapping of message level to message tag, which is typically rendered as a CSS class in HTML. If you specify a value, it will extend the default. This means you only have to specify those values which you need to override. See Displaying messages above for more details.

Important

If you override MESSAGE_TAGS in your settings file and rely on any of the built-in constants, you must import the constants module directly to avoid the potential for circular imports, e.g.:

from django.contrib.messages import constants as message_constants
MESSAGE_TAGS = {message_constants.INFO: ''}

If desired, you may specify the numeric values for the constants directly according to the values in the above constants table.

Sessions

Settings for django.contrib.sessions.

SESSION_CACHE_ALIAS

默认: 默认缓存设置

使用 缓存存储会话时, 使用何种缓存

SESSION_ENGINE

 默认:django.contrib.sessions.backends.db

控制Django 在哪里存储会话数据。包含的引擎有:

  • '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'

更多细节参见配置会话引擎

SESSION_EXPIRE_AT_BROWSER_CLOSE

Default: False

当用户关闭浏览器时是否使会话过期See Browser-length sessions vs. persistent sessions.

SESSION_FILE_PATH

Default: None

If you’re using file-based session storage, this sets the directory in which Django will store session data. When the default value (None) is used, Django will use the standard temporary directory for the system.

SESSION_SAVE_EVERY_REQUEST

Default: False

Whether to save the session data on every request. If this is False (default), then the session data will only be saved if it has been modified – that is, if any of its dictionary values have been assigned or deleted.

SESSION_SERIALIZER

Default: 'django.contrib.sessions.serializers.JSONSerializer'

Full import path of a serializer class to use for serializing session data. Included serializers are:

  • 'django.contrib.sessions.serializers.PickleSerializer'
  • 'django.contrib.sessions.serializers.JSONSerializer'

See Session serialization for details, including a warning regarding possible remote code execution when using PickleSerializer.

Sites

django.contrib.sites 的设置。

SITE_ID

默认:未定义

当前站点在django_site 数据库表中的ID,为一个整数。这是用来让应用程序数据可以连接到特定的网站和一个单一的数据库可以管理多个站点的内容

Static files

设置为 django.contrib.staticfiles.

STATIC_ROOT

默认: None

collectstatic用于部署而收集的静态文件的目录的绝对路径。

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

如果 staticfiles 启用这个服务应用程序 (默认) collectstatic 管理命令将收集的静态文件到这个目录查看如何在 managing static files有关使用的更多细节。

提醒

这应该是一个 (空目录) 的目录,用于从原始目录收集静态文件到这个目录,便于部署。不是永久存储静态文件的地方。You should do that in directories that will be found by staticfiles’s finders, which by default, are 'static/' app sub-directories and any directories you include in STATICFILES_DIRS).

STATIC_URL

默认值: None

用来访问位于STATIC_ROOT中的静态文件的URL。

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

If not None, this will be used as the base path for asset definitions (the Media class) and the staticfiles app.

如果设置为非空值时,结尾必须是反斜线。

You may need to configure these files to be served in development and will definitely need to do so in production.

STATICFILES_DIRS

Default: []

This setting defines the additional locations the staticfiles app will traverse if the FileSystemFinder finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view.

This should be set to a list or tuple of strings that contain full paths to your additional files directory(ies) e.g.:

STATICFILES_DIRS = (
    "/home/special.polls.com/polls/static",
    "/home/polls.com/polls/static",
    "/opt/webfiles/common",
)

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

Prefixes (optional)

In case you want to refer to files in one of the locations with an additional namespace, you can optionally provide a prefix as (prefix, path) tuples, e.g.:

STATICFILES_DIRS = (
    # ...
    ("downloads", "/opt/webfiles/stats"),
)

舉例來說,假設您將STATIC_URL設值為 '/static/',那麼collectstatic指令將會收集靜態檔案至STATIC_ROOT的子目錄'downloads'

This would allow you to refer to the local file '/opt/webfiles/stats/polls_20101022.tar.gz' with '/static/downloads/polls_20101022.tar.gz' in your templates, e.g.:

<a href="{% static "downloads/polls_20101022.tar.gz" %}">

STATICFILES_STORAGE

Default: 'django.contrib.staticfiles.storage.StaticFilesStorage'

The file storage engine to use when collecting static files with the collectstatic management command.

A ready-to-use instance of the storage backend defined in this setting can be found at django.contrib.staticfiles.storage.staticfiles_storage.

For an example, see Serving static files from a cloud service or CDN.

STATICFILES_FINDERS

默认值:

("django.contrib.staticfiles.finders.FileSystemFinder",
 "django.contrib.staticfiles.finders.AppDirectoriesFinder")

finder后端列表,不同finder用来在不同的位置搜索静态文件。

默认设置是在 STATICFILES_DIRS (使用 django.contrib.staticfiles.finders.FileSystemFinder) 和每个应用的子目录 static (使用 django.contrib.staticfiles.finders.AppDirectoriesFinder)中搜索.如果存在多个具有相同名称的文件,则将使用找到的第一个文件。

查找器 django.contrib.staticfiles.finders.DefaultStorageFinder默认情况下是被禁用的.如果添加到您的STATICFILES_FINDERS设置,它将在默认文件存储中查找由DEFAULT_FILE_STORAGE设置定义的静态文件。

注意

使用AppDirectoriesFinder查找工具时,请确保您的应用可以通过静态文件找到。只需将应用程式新增至您网站的INSTALLED_APPS设定即可。

静态文件查找器目前被认为是一个私有接口,因此这个接口是未被文档记录的。

Core Settings Topical Index