系统检查框架是一套用于验证 Django 项目的静态检查。它检测常见的问题,并提供如何修复这些问题的提示。该框架是可扩展的,所以你可以很容易地添加自己的检查。
关于如何添加自己的检查并与 Django 的系统检查集成的细节,请看 系统检查主题指南。
CheckMessage
¶CheckMessage
(level, msg, hint=None, obj=None, id=None)¶系统检查提出的警告和错误必须是 CheckMessage
的实例。一个实例封装了一个单一的可报告的错误或警告。它还提供适用于该信息的上下文和提示,以及用于过滤目的的唯一标识符。
构造方法的参数:
level
DEBUG
、INFO
、WARNING
、ERROR
、CRITICAL
。如果级别大于或等于 ERROR
,那么 Django 将阻止管理命令的执行。等级小于 ``ERROR```的消息(即警告)会被报告到控制台,但可以被静默。msg
hint
None
值。obj
str__()
方法的任何其他对象。该方法在报告所有消息时使用,其结果在消息之前。id
applabel.X001
的模式,其中 X
是字母 CEWID
中的一个,表示消息的严重性(C
表示严重,E
表示错误等)。这个数字可由应用程序分配,但在该应用程序内应是唯一的。有一些子类可以使创建具有通用级别的消息更容易。当使用它们时,你可以省略 level
参数,因为它已被类名所隐含。
Debug
(msg, hint=None, obj=None, id=None)¶Info
(msg, hint=None, obj=None, id=None)¶Warning
(msg, hint=None obj=None, id=None)¶Error
(msg, hint=None, obj=None, id=None)¶Critical
(msg, hint=None, obj=None, id=None)¶Django 的系统检查按以下标签组织:
admin
:检查所有管理站点的声明。async_support
: 检查异步相关配置。caches
:检查缓存相关的配置。compatibility
:标记版本升级可能导致的问题。database
:检查与数据库有关的配置问题。默认情况下不运行数据库检查,因为数据库检查的工作比普通检查的静态代码分析更多。只有通过 migrate
命令或在调用 check
命令时使用 --database
选项指定配置的数据库别名时,才会运行数据库检查。models
:检查模型、字段和管理器定义。security
:检查安全相关配置。signals
:检查信号声明和处理器注册信息。staticfiles
:检查 django.contrib.staticfiles
配置。templates
:检查模板相关配置。translation
:检查翻译相关配置。urls
:检查 URL 配置。一些可能通过多个标签同时注册的检查项。
增加了 async_support
标签。
database
检查现在只对使用 check --database
选项指定的数据库别名运行。
以下检查验证了你对 异步支持 的配置:
DJANGO_ALLOW_ASYNC_UNSAFE
环境变量。这将禁用 异步安全保护。兼容性检查警告那些升级 Django 后可能出现的问题。
<pattern>
有一个 route
包含 (?P<
、以 ^
开始或以 $
结束。这可能是在从 url()
迁移到 path()
时的一个疏忽。如果你使用的是 MySQL 或 MariaDB,将执行以下检查:
CharField
有一个 max_length
> 255。这项检查在 Django 3.1 中 被改为 mysql.W003
,因为真正的最大尺寸取决于许多因素。<alias>
未设置为严格模式。另见 设置 sql_mode。CharField
有 max_length
> 255。"__"
。pk
是保留关键字,不能作为字段名使用。choices
必须是可迭代对象(例如,列表或元组)。choices
必须是一个可迭代对象,返回由 (actual value, human readable name)
构成的元组。db_index
必须是 None
,True
或 False
。null = True
。validators
必须都是可调用的。max_length
太小,无法容纳 choices
中的最长值(<count>
字符)。<field>
默认值应该是一个可调用对象,而不是一个实例,这样就不会在所有字段实例之间共享。AutoField
必须设置 primary_key=True。BooleanField
不接受空值。这项检查出现在 Django 2.1 中增加对空值的支持之前。CharField
必须定义一个 max_length
属性。max_length
必须是个正整数。max_length
在使用 <integer field type>
时会被忽略。DecimalField
必须定义一个 decimal_places
属性。decimal_places
必须是个非负整数。DecimalField
必须定义一个 max_digits
属性。max_digits
必须是一个非负整数。max_digits
必须大于或等于 decimal_places
。FilePathField
的 allow_files
或 allow_folders
必须有一个被设为 True。GenericIPAddressField
不允许 null 值,那么它也不接受空值,因为空值被保存为 null。auto_now
、auto_now_add
和 default
等选项是相互排斥的。这些选项只能有一个。<database>
并不支持在 <field data type>
列上创建数据库索引。BinaryField
的 default
不能是字符串。使用字节内容代替。<database>
不支持 JSONField
。IPAddressField
已被删除,但历史迁移中的支持除外。IPAddressField
已被废弃。在 Django 1.9 中,将取消对它的支持(除了历史迁移)。这个检查出现在 Django 1.7 和 1.8 中。CommaSeparatedIntegerField
已被废弃。在 Django 2.0 中,对它的支持将被删除(除了在历史迁移中)。这个检查出现在 Django 1.10 和 1.11 中。CommaSeparatedIntegerField
已被删除,但历史迁移中的支持除外。FloatRangeField
已被废弃,将在 Django 3.1 中删除。这项检查出现在 Django 2.2 和 3.0 中。NullBooleanField
已被废弃。在 Django 4.0 中,将取消对它的支持(历史迁移除外)。django.contrib.postgres.fields.JSONField
已被废弃。对它的支持(除了在历史迁移中)将在 Django 4.0 中被删除。unique
不是 FileField
的有效参数。这项检查在 Django 1.11 中已被删除。primary_key
对于 FileField
来说不是个有效的参数。FileField
的 upload_to
参数必须是个相对路径,而不是一个相对路径。ImageField
,因为未安装 Pillow。<swappable>
不是表单 app_label.app_name
。<SETTING>
references <model>
, which has not been
installed, or is abstract.<app_label>.<model>
.id
can only be used as a field name if the field also
sets primary_key=True
.<field name>
from parent model <model>
clashes with the field <field name>
from parent model <model>
.<model>
的字段 <field name>
冲突的字段。<column name>
被其它字段使用的字段 <field name>
。index_together
必须是个列表或元组。index_together
元素都必须是列表或元组。unique_together
必须是个列表或元组。unique_together
元素都必须是列表或元组。indexes/index_together/unique_together
指向了不存在的字段 <field name>
。indexes/index_together/unique_together
指向一个 ManyToManyField
<field name>
,但此选项不支持 ManyToManyField
。ordering
必须是个元组或列表(即便你只想按照一个字段进行排序)。ordering
refers to the nonexistent field, related field,
or lookup <field name>
.indexes/index_together/unique_together
refers to field
<field_name>
which is not local to model <model>
.<model>
contains model fields.<field>
.
Maximum length is <maximum length>
for database <alias>
.<M2M field>
. Maximum length is <maximum length>
for database
<alias>
.<model>.check()
class method is currently overridden.ordering
and order_with_respect_to
cannot be used
together.<function>
contains a lazy reference to
<app label>.<model>
, but app <app label>
isn't installed or
doesn't provide model <model>
.<model>
cannot start or end with an
underscore as it collides with the query lookup syntax.<model>
cannot contain double underscores
as it collides with the query lookup syntax.<property name>
clashes with a related
field accessor.primary_key=True
.<database>
does not support check constraints.db_table
<db_table>
is used by multiple models:
<model list>
.<index>
is not unique for model <model>
.<index>
is not unique amongst models:
<model list>
.<constraint>
is not unique for model
<model>
.<constraint>
is not unique amongst
models: <model list>
.<index>
cannot start with an underscore
or a number.<index>
cannot be longer than
<max_length>
characters.db_table
<db_table>
is used by multiple models:
<model list>
.<database>
does not support unique constraints with
conditions.<database>
does not support indexes with conditions.<database>
does not support deferrable unique
constraints.The security checks do not make your site secure. They do not audit code, do intrusion detection, or do anything particularly complex. Rather, they help perform an automated, low-hanging-fruit checklist, that can help you to improve your site's security.
Some of these checks may not be appropriate for your particular deployment
configuration. For instance, if you do your HTTP to HTTPS redirection in a load
balancer, it'd be irritating to be constantly warned about not having enabled
SECURE_SSL_REDIRECT
. Use SILENCED_SYSTEM_CHECKS
to
silence unneeded checks.
The following checks are run if you use the check --deploy
option:
django.middleware.security.SecurityMiddleware
in your
MIDDLEWARE
so the SECURE_HSTS_SECONDS
,
SECURE_CONTENT_TYPE_NOSNIFF
, SECURE_BROWSER_XSS_FILTER
,
SECURE_REFERRER_POLICY
, and SECURE_SSL_REDIRECT
settings will have no effect.django.middleware.clickjacking.XFrameOptionsMiddleware
in your
MIDDLEWARE
, so your pages will not be served with an
'x-frame-options'
header. Unless there is a good reason for your
site to be served in a frame, you should consider enabling this
header to help prevent clickjacking attacks.django.middleware.csrf.CsrfViewMiddleware
is not in your
MIDDLEWARE
). Enabling the middleware is the safest
approach to ensure you don't leave any holes.SECURE_HSTS_SECONDS
setting. If your entire site is served only
over SSL, you may want to consider setting a value and enabling HTTP
Strict Transport Security. Be sure to read
the documentation first; enabling HSTS carelessly can cause serious,
irreversible problems.SECURE_HSTS_INCLUDE_SUBDOMAINS
setting to True
. Without this,
your site is potentially vulnerable to attack via an insecure connection to a
subdomain. Only set this to True
if you are certain that all subdomains of
your domain should be served exclusively via SSL.SECURE_CONTENT_TYPE_NOSNIFF
setting is not
set to True
, so your pages will not be served with an
'X-Content-Type-Options: nosniff'
header. You should consider enabling
this header to prevent the browser from identifying content types incorrectly.SECURE_BROWSER_XSS_FILTER
setting is not
set to True
, so your pages will not be served with an
'X-XSS-Protection: 1; mode=block'
header. You should consider enabling
this header to activate the browser's XSS filtering and help prevent XSS
attacks. This check is removed in Django 3.0 as the X-XSS-Protection
header is no longer honored by modern browsers.SECURE_SSL_REDIRECT
setting is not set to
True
. Unless your site should be available over both SSL and non-SSL
connections, you may want to either set this setting to True
or configure
a load balancer or reverse-proxy server to redirect all connections to HTTPS.SECRET_KEY
has less than 50 characters or
less than 5 unique characters. Please generate a long and random
SECRET_KEY
, otherwise many of Django's security-critical features will be
vulnerable to attack.django.contrib.sessions
in your
INSTALLED_APPS
but you have not set
SESSION_COOKIE_SECURE
to True
. Using a secure-only session
cookie makes it more difficult for network traffic sniffers to hijack user
sessions.django.contrib.sessions.middleware.SessionMiddleware
in your
MIDDLEWARE
, but you have not set SESSION_COOKIE_SECURE
to True
. Using a secure-only session cookie makes it more difficult for
network traffic sniffers to hijack user sessions.SESSION_COOKIE_SECURE
is not set to True
.
Using a secure-only session cookie makes it more difficult for network traffic
sniffers to hijack user sessions.django.contrib.sessions
in your
INSTALLED_APPS
, but you have not set
SESSION_COOKIE_HTTPONLY
to True
. Using an HttpOnly
session
cookie makes it more difficult for cross-site scripting attacks to hijack user
sessions.django.contrib.sessions.middleware.SessionMiddleware
in your
MIDDLEWARE
, but you have not set SESSION_COOKIE_HTTPONLY
to True
. Using an HttpOnly
session cookie makes it more difficult for
cross-site scripting attacks to hijack user sessions.SESSION_COOKIE_HTTPONLY
is not set to True
.
Using an HttpOnly
session cookie makes it more difficult for cross-site
scripting attacks to hijack user sessions.CSRF_COOKIE_SECURE
is not set to True
.
Using a secure-only CSRF cookie makes it more difficult for network traffic
sniffers to steal the CSRF token.CSRF_COOKIE_HTTPONLY
is not set to True
.
Using an HttpOnly
CSRF cookie makes it more difficult for cross-site
scripting attacks to steal the CSRF token. This check is removed in Django
1.11 as the CSRF_COOKIE_HTTPONLY
setting offers no practical
benefit.DEBUG
set to True
in
deployment.django.middleware.clickjacking.XFrameOptionsMiddleware
in your
MIDDLEWARE
, but X_FRAME_OPTIONS
is not set to
'DENY'
. Unless there is a good reason for your site to serve other parts
of itself in a frame, you should change it to 'DENY'
.ALLOWED_HOSTS
must not be empty in deployment.SECURE_HSTS_PRELOAD
setting to True
. Without this, your site
cannot be submitted to the browser preload list.SECURE_REFERRER_POLICY
setting. Without this, your site will not send a Referrer-Policy header. You
should consider enabling this header to protect user privacy.SECURE_REFERRER_POLICY
setting
to an invalid value.The following checks verify that your security-related settings are correctly configured:
DEFAULT_HASHING_ALGORITHM
must be 'sha1'
or
'sha256'
.<handler>
was connected to the <signal>
signal with
a lazy reference to the sender <app label>.<model>
, but app <app label>
isn't installed or doesn't provide model <model>
.The following checks are performed on your translation configuration:
LANGUAGE_CODE
setting: <value>
.LANGUAGES
setting: <value>
.LANGUAGES_BIDI
setting: <value>
.LANGUAGE_CODE
setting that is not in the LANGUAGES
setting.以下检查项针对你的 URL 配置执行:
<pattern>
uses
include()
with a route
ending with a $
. Remove the
dollar from the route
to avoid problems including URLs.<pattern>
has a route
beginning with
a /
. Remove this slash as it is unnecessary. If this pattern is targeted
in an include()
, ensure the include()
pattern has a trailing /
.<pattern>
has a name
including a :
. Remove the colon, to avoid ambiguous namespace
references.<pattern>
is invalid. Ensure that
urlpatterns
is a list of path()
and/or
re_path()
instances.<namespace>
isn't unique. You may not be
able to reverse all URLs in this namespace.MEDIA_URL
/ STATIC_URL
setting must
end with a slash.handlerXXX
view 'path.to.view'
does not
take the correct number of arguments (…).handlerXXX
view 'path.to.view'
could not be
imported.contrib
应用检查¶admin
¶后台检查项均作为 admin
标签的一部分执行。
以下检查项在每个通过后台站点注册的 ModelAdmin
(或其子类)上执行。
raw_id_fields
的值必须是个列表或元组。raw_id_fields[n]
的值指向 <field name>
,它并不是 <model>
的属性。raw_id_fields[n]
的值必须是个外键或一个多对多字段。fields
的值必须是列表或元组。fieldsets
和 fields
都是定制的。fields
的值包含了重复字段。fieldsets
的值必须是个列表或元组。fieldsets[n]
的值必须是个列表或元组。fieldsets[n]
的值的长度必须是 2。fieldsets[n][1]
的值必须是个字典。fieldsets[n][1]
的值必须包含键 fields
。fieldsets[n][1]
中有重复字段。fields[n]/fieldsets[n][m]
cannot include the
ManyToManyField
<field name>
, because that field manually specifies a
relationship model.exclude
的值必须是个列表或元组。exclude
的值必须包含重复字段。form
的值必须继承自 BaseModelForm
。filter_vertical
的值必须是个列表或元组。filter_horizontal
的值必须是个列表或元组。filter_vertical[n]/filter_horizontal[n]
refers to <field name>
, which is not an attribute of <model>
.filter_vertical[n]/filter_horizontal[n]
must be a many-to-many field.radio_fields
must be a dictionary.radio_fields
refers to <field name>
,
which is not an attribute of <model>
.radio_fields
refers to <field name>
,
which is not instance of ForeignKey
, and does not have a choices
definition.radio_fields[<field name>]
must be either
admin.HORIZONTAL
or admin.VERTICAL
.view_on_site
must be either a callable or a
boolean value.prepopulated_fields
must be a dictionary.prepopulated_fields
refers to
<field name>
, which is not an attribute of <model>
.prepopulated_fields
refers to
<field name>
, which must not be a DateTimeField
, a ForeignKey
,
a OneToOneField
, or a ManyToManyField
field.prepopulated_fields[<field name>]
must be a
list or tuple.prepopulated_fields
refers to
<field name>
, which is not an attribute of <model>
.ordering
must be a list or tuple.ordering
has the random ordering marker
?
, but contains other fields as well.ordering
refers to <field name>
, which
is not an attribute of <model>
.readonly_fields
must be a list or tuple.readonly_fields[n]
is not a callable, an
attribute of <ModelAdmin class>
, or an attribute of <model>
.autocomplete_fields
must be a list or tuple.autocomplete_fields[n]
refers to
<field name>
, which is not an attribute of <model>
.autocomplete_fields[n]
must be a foreign
key or a many-to-many field.<model>
has to be registered to be
referenced by <modeladmin>.autocomplete_fields
.<modeladmin>
must define search_fields
, because
it's referenced by <other_modeladmin>.autocomplete_fields
.ModelAdmin
¶The following checks are performed on any
ModelAdmin
that is registered
with the admin site:
save_as
的值必须是个布尔值。save_on_top
的值必须是个布尔值。inlines
的值必须是个列表或元组。<InlineModelAdmin class>
必须继承自 InlineModelAdmin
。<InlineModelAdmin class>
必须有个 model
属性。<InlineModelAdmin class>.model
的值必须是个 Model
。list_display
的值必须是个列表或元组。list_display[n]
refers to <label>
,
which is not a callable, an attribute of <ModelAdmin class>
, or an
attribute or method on <model>
.list_display[n]
的值绝对不能是个 ManyToManyField
字段。list_display_links
must be a list, a tuple,
or None
.list_display_links[n]
refers to <label>
,
which is not defined in list_display
.list_filter
must be a list or tuple.list_filter[n]
must inherit from
ListFilter
.list_filter[n]
must not inherit from
FieldListFilter
.list_filter[n][1]
must inherit from
FieldListFilter
.list_filter[n]
refers to <label>
,
which does not refer to a Field.list_select_related
must be a boolean,
tuple or list.list_per_page
must be an integer.list_max_show_all
must be an integer.list_editable
must be a list or tuple.list_editable[n]
refers to <label>
,
which is not an attribute of <model>
.list_editable[n]
refers to <label>
,
which is not contained in list_display
.list_editable[n]
cannot be in both
list_editable
and list_display_links
.list_editable[n]
refers to the first field
in list_display
(<label>
), which cannot be used unless
list_display_links
is set.list_editable[n]
refers to <field name>
,
which is not editable through the admin.search_fields
must be a list or tuple.date_hierarchy
refers to <field name>
,
which does not refer to a Field.date_hierarchy
must be a DateField
or
DateTimeField
.<modeladmin>
must define a has_<foo>_permission()
method for the <action>
action.__name__
attributes of actions defined in
<modeladmin>
must be unique. Name <name>
is not unique.InlineModelAdmin
¶The following checks are performed on any
InlineModelAdmin
that is registered as an
inline on a ModelAdmin
.
<field name>
, because it is the
foreign key to the parent model <app_label>.<model>
.<model>
has no ForeignKey
to <parent model>
./
<model>
has more than one ForeignKey
to <parent model>
. You must
specify a fk_name
attribute.extra
must be an integer.max_num
must be an integer.min_num
must be an integer.formset
must inherit from
BaseModelFormSet
.GenericInlineModelAdmin
¶The following checks are performed on any
GenericInlineModelAdmin
that is
registered as an inline on a ModelAdmin
.
'ct_field'
references <label>
, which is not a field
on <model>
.'ct_fk_field'
references <label>
, which is not a
field on <model>
.<model>
has no GenericForeignKey
.<model>
has no GenericForeignKey
using content type
field <field name>
and object ID field <field name>
.AdminSite
¶The following checks are performed on the default
AdminSite
:
django.contrib.contenttypes
must be in
INSTALLED_APPS
in order to use the admin application.django.contrib.auth.context_processors.auth
must be enabled in DjangoTemplates
(TEMPLATES
) if using the default auth backend in order to use the
admin application.django.template.backends.django.DjangoTemplates
instance must be configured in TEMPLATES
in order to use the
admin application.django.contrib.messages.context_processors.messages
must be enabled in DjangoTemplates
(TEMPLATES
) in order to use the admin application.django.contrib.auth
must be in
INSTALLED_APPS
in order to use the admin application.django.contrib.messages
must be in
INSTALLED_APPS
in order to use the admin application.django.contrib.auth.middleware.AuthenticationMiddleware
must be in
MIDDLEWARE
in order to use the admin application.django.contrib.messages.middleware.MessageMiddleware
must be in MIDDLEWARE
in order to use the admin application.django.contrib.sessions.middleware.SessionMiddleware
must be in MIDDLEWARE
in order to use the admin application.django.template.context_processors.request
must be
enabled in DjangoTemplates
(TEMPLATES
) in order to use the admin navigation sidebar.auth
¶REQUIRED_FIELDS
must be a list or tuple.USERNAME_FIELD
for a custom user
model must not be included in REQUIRED_FIELDS
.<field>
must be unique because it is named as the
USERNAME_FIELD
.<field>
is named as the USERNAME_FIELD
, but it is not
unique.<codename>
clashes with a builtin
permission for model <model>
.<codename>
is duplicated for model
<model>
.verbose_name
of model <model>
must be at most
244 characters for its builtin permission names
to be at most 255 characters.<name>
of model <model>
is longer
than 255 characters.<User model>.is_anonymous
must be an attribute or property
rather than a method. Ignoring this is a security issue as anonymous users
will be treated as authenticated!<User model>.is_authenticated
must be an attribute or
property rather than a method. Ignoring this is a security issue as anonymous
users will be treated as authenticated!<model>
must be at most 93 characters
for its builtin permission names to be at most 100 characters.<codename>
of model <model>
is longer than 100 characters.contenttypes
¶The following checks are performed when a model contains a
GenericForeignKey
or
GenericRelation
:
GenericForeignKey
object ID references the
nonexistent field <field>
.GenericForeignKey
content type references the
nonexistent field <field>
.<field>
is not a ForeignKey
.<field>
is not a ForeignKey
to
contenttypes.ContentType
.postgres
¶The following checks are performed on django.contrib.postgres
model
fields:
<field>
default should be a callable instead of an
instance so that it's not shared between all field instances. This check was
changed to fields.E010
in Django 3.1.sites
¶The following checks are performed on any model using a
CurrentSiteManager
:
CurrentSiteManager
could not find a field named
<field name>
.CurrentSiteManager
cannot use <field>
as it is not a
foreign key or a many-to-many field.staticfiles
¶The following checks verify that django.contrib.staticfiles
is correctly
configured:
STATICFILES_DIRS
setting is not a tuple
or list.STATICFILES_DIRS
setting should not
contain the STATIC_ROOT
setting.<prefix>
in the
STATICFILES_DIRS
setting must not end with a slash.3月 04, 2021