| 1 |
====================== |
| 2 |
System check framework |
| 3 |
====================== |
| 4 |
|
| 5 |
.. module:: django.core.checks |
| 6 |
|
| 7 |
The system check framework is a set of static checks for validating Django |
| 8 |
projects. It detects common problems and provides hints for how to fix them. |
| 9 |
The framework is extensible so you can easily add your own checks. |
| 10 |
|
| 11 |
Checks can be triggered explicitly via the :djadmin:`check` command. Checks are |
| 12 |
triggered implicitly before most commands, including :djadmin:`runserver` and |
| 13 |
:djadmin:`migrate`. For performance reasons, checks are not run as part of the |
| 14 |
WSGI stack that is used in deployment. If you need to run system checks on your |
| 15 |
deployment server, trigger them explicitly using :djadmin:`check`. |
| 16 |
|
| 17 |
Serious errors will prevent Django commands (such as :djadmin:`runserver`) from |
| 18 |
running at all. Minor problems are reported to the console. If you have inspected |
| 19 |
the cause of a warning and are happy to ignore it, you can hide specific warnings |
| 20 |
using the :setting:`SILENCED_SYSTEM_CHECKS` setting in your project settings file. |
| 21 |
|
| 22 |
A full list of all checks that can be raised by Django can be found in the |
| 23 |
:doc:`System check reference </ref/checks>`. |
| 24 |
|
| 25 |
Writing your own checks |
| 26 |
======================= |
| 27 |
|
| 28 |
The framework is flexible and allows you to write functions that perform |
| 29 |
any other kind of check you may require. The following is an example stub |
| 30 |
check function:: |
| 31 |
|
| 32 |
from django.core.checks import Error, register |
| 33 |
|
| 34 |
|
| 35 |
@register() |
| 36 |
def example_check(app_configs, **kwargs): |
| 37 |
errors = [] |
| 38 |
# ... your check logic here |
| 39 |
if check_failed: |
| 40 |
errors.append( |
| 41 |
Error( |
| 42 |
"an error", |
| 43 |
hint="A hint.", |
| 44 |
obj=checked_object, |
| 45 |
id="myapp.E001", |
| 46 |
) |
| 47 |
) |
| 48 |
return errors |
| 49 |
|
| 50 |
The check function *must* accept an ``app_configs`` argument; this argument is |
| 51 |
the list of applications that should be inspected. If ``None``, the check must |
| 52 |
be run on *all* installed apps in the project. |
| 53 |
|
| 54 |
The check will receive a ``databases`` keyword argument. This is a list of |
| 55 |
database aliases whose connections may be used to inspect database level |
| 56 |
configuration. If ``databases`` is ``None``, the check must not use any |
| 57 |
database connections. |
| 58 |
|
| 59 |
The ``**kwargs`` argument is required for future expansion. |
| 60 |
|
| 61 |
Messages |
| 62 |
-------- |
| 63 |
|
| 64 |
The function must return a list of messages. If no problems are found as a result |
| 65 |
of the check, the check function must return an empty list. |
| 66 |
|
| 67 |
The warnings and errors raised by the check method must be instances of |
| 68 |
:class:`~django.core.checks.CheckMessage`. An instance of |
| 69 |
:class:`~django.core.checks.CheckMessage` encapsulates a single reportable |
| 70 |
error or warning. It also provides context and hints applicable to the |
| 71 |
message, and a unique identifier that is used for filtering purposes. |
| 72 |
|
| 73 |
The concept is very similar to messages from the :doc:`message framework |
| 74 |
</ref/contrib/messages>` or the :doc:`logging framework </topics/logging>`. |
| 75 |
Messages are tagged with a ``level`` indicating the severity of the message. |
| 76 |
|
| 77 |
There are also shortcuts to make creating messages with common levels easier. |
| 78 |
When using these classes you can omit the ``level`` argument because it is |
| 79 |
implied by the class name. |
| 80 |
|
| 81 |
* :class:`Debug` |
| 82 |
* :class:`Info` |
| 83 |
* :class:`Warning` |
| 84 |
* :class:`Error` |
| 85 |
* :class:`Critical` |
| 86 |
|
| 87 |
.. _registering-labeling-checks: |
| 88 |
|
| 89 |
Registering and labeling checks |
| 90 |
------------------------------- |
| 91 |
|
| 92 |
Lastly, your check function must be registered explicitly with system check |
| 93 |
registry. Checks should be registered in a file that's loaded when your |
| 94 |
application is loaded; for example, in the :meth:`AppConfig.ready() |
| 95 |
<django.apps.AppConfig.ready>` method. |
| 96 |
|
| 97 |
.. function:: register(*tags)(function) |
| 98 |
|
| 99 |
You can pass as many tags to ``register`` as you want in order to label your |
| 100 |
check. Tagging checks is useful since it allows you to run only a certain |
| 101 |
group of checks. For example, to register a compatibility check, you would |
| 102 |
make the following call:: |
| 103 |
|
| 104 |
from django.core.checks import register, Tags |
| 105 |
|
| 106 |
|
| 107 |
@register(Tags.compatibility) |
| 108 |
def my_check(app_configs, **kwargs): |
| 109 |
# ... perform compatibility checks and collect errors |
| 110 |
return errors |
| 111 |
|
| 112 |
You can register "deployment checks" that are only relevant to a production |
| 113 |
settings file like this:: |
| 114 |
|
| 115 |
@register(Tags.security, deploy=True) |
| 116 |
def my_check(app_configs, **kwargs): ... |
| 117 |
|
| 118 |
These checks will only be run if the :option:`check --deploy` option is used. |
| 119 |
|
| 120 |
You can also use ``register`` as a function rather than a decorator by |
| 121 |
passing a callable object (usually a function) as the first argument |
| 122 |
to ``register``. |
| 123 |
|
| 124 |
The code below is equivalent to the code above:: |
| 125 |
|
| 126 |
def my_check(app_configs, **kwargs): ... |
| 127 |
|
| 128 |
|
| 129 |
register(my_check, Tags.security, deploy=True) |
| 130 |
|
| 131 |
.. _field-checking: |
| 132 |
|
| 133 |
Field, model, manager, template engine, and database checks |
| 134 |
----------------------------------------------------------- |
| 135 |
|
| 136 |
In some cases, you won't need to register your check function -- you can |
| 137 |
piggyback on an existing registration. |
| 138 |
|
| 139 |
Fields, models, model managers, template engines, and database backends all |
| 140 |
implement a ``check()`` method that is already registered with the check |
| 141 |
framework. If you want to add extra checks, you can extend the implementation |
| 142 |
on the base class, perform any extra checks you need, and append any messages |
| 143 |
to those generated by the base class. It's recommended that you delegate each |
| 144 |
check to separate methods. |
| 145 |
|
| 146 |
Consider an example where you are implementing a custom field named |
| 147 |
``RangedIntegerField``. This field adds ``min`` and ``max`` arguments to the |
| 148 |
constructor of ``IntegerField``. You may want to add a check to ensure that users |
| 149 |
provide a min value that is less than or equal to the max value. The following |
| 150 |
code snippet shows how you can implement this check:: |
| 151 |
|
| 152 |
from django.core import checks |
| 153 |
from django.db import models |
| 154 |
|
| 155 |
|
| 156 |
class RangedIntegerField(models.IntegerField): |
| 157 |
def __init__(self, min=None, max=None, **kwargs): |
| 158 |
super().__init__(**kwargs) |
| 159 |
self.min = min |
| 160 |
self.max = max |
| 161 |
|
| 162 |
def check(self, **kwargs): |
| 163 |
# Call the superclass |
| 164 |
errors = super().check(**kwargs) |
| 165 |
|
| 166 |
# Do some custom checks and add messages to `errors`: |
| 167 |
errors.extend(self._check_min_max_values(**kwargs)) |
| 168 |
|
| 169 |
# Return all errors and warnings |
| 170 |
return errors |
| 171 |
|
| 172 |
def _check_min_max_values(self, **kwargs): |
| 173 |
if self.min is not None and self.max is not None and self.min > self.max: |
| 174 |
return [ |
| 175 |
checks.Error( |
| 176 |
"min greater than max.", |
| 177 |
hint="Decrease min or increase max.", |
| 178 |
obj=self, |
| 179 |
id="myapp.E001", |
| 180 |
) |
| 181 |
] |
| 182 |
# When no error, return an empty list |
| 183 |
return [] |
| 184 |
|
| 185 |
If you wanted to add checks to a model manager, you would take the same |
| 186 |
approach on your subclass of :class:`~django.db.models.Manager`. |
| 187 |
|
| 188 |
If you want to add a check to a model class, the approach is *almost* the same: |
| 189 |
the only difference is that the check is a classmethod, not an instance method:: |
| 190 |
|
| 191 |
class MyModel(models.Model): |
| 192 |
@classmethod |
| 193 |
def check(cls, **kwargs): |
| 194 |
errors = super().check(**kwargs) |
| 195 |
# ... your own checks ... |
| 196 |
return errors |
| 197 |
|
| 198 |
.. versionchanged:: 5.1 |
| 199 |
|
| 200 |
In older versions, template engines didn't implement a ``check()`` method. |
| 201 |
|
| 202 |
Writing tests |
| 203 |
------------- |
| 204 |
|
| 205 |
Messages are comparable. That allows you to easily write tests:: |
| 206 |
|
| 207 |
from django.core.checks import Error |
| 208 |
|
| 209 |
errors = checked_object.check() |
| 210 |
expected_errors = [ |
| 211 |
Error( |
| 212 |
"an error", |
| 213 |
hint="A hint.", |
| 214 |
obj=checked_object, |
| 215 |
id="myapp.E001", |
| 216 |
) |
| 217 |
] |
| 218 |
self.assertEqual(errors, expected_errors) |
| 219 |
|
| 220 |
Writing integration tests |
| 221 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 222 |
|
| 223 |
Given the need to register certain checks when the application loads, it can be |
| 224 |
useful to test their integration within the system checks framework. This can |
| 225 |
be accomplished by using the :func:`~django.core.management.call_command` |
| 226 |
function. |
| 227 |
|
| 228 |
For example, this test demonstrates that the :setting:`SITE_ID` setting must be |
| 229 |
an integer, a built-in :ref:`check from the sites framework |
| 230 |
<sites-system-checks>`:: |
| 231 |
|
| 232 |
from django.core.management import call_command |
| 233 |
from django.core.management.base import SystemCheckError |
| 234 |
from django.test import SimpleTestCase, modify_settings, override_settings |
| 235 |
|
| 236 |
|
| 237 |
class SystemCheckIntegrationTest(SimpleTestCase): |
| 238 |
@override_settings(SITE_ID="non_integer") |
| 239 |
@modify_settings(INSTALLED_APPS={"prepend": "django.contrib.sites"}) |
| 240 |
def test_non_integer_site_id(self): |
| 241 |
message = "(sites.E101) The SITE_ID setting must be an integer." |
| 242 |
with self.assertRaisesMessage(SystemCheckError, message): |
| 243 |
call_command("check") |
| 244 |
|
| 245 |
Consider the following check which issues a warning on deployment if a custom |
| 246 |
setting named ``ENABLE_ANALYTICS`` is not set to ``True``:: |
| 247 |
|
| 248 |
from django.conf import settings |
| 249 |
from django.core.checks import Warning, register |
| 250 |
|
| 251 |
|
| 252 |
@register("myapp", deploy=True) |
| 253 |
def check_enable_analytics_is_true_on_deploy(app_configs, **kwargs): |
| 254 |
errors = [] |
| 255 |
if getattr(settings, "ENABLE_ANALYTICS", None) is not True: |
| 256 |
errors.append( |
| 257 |
Warning( |
| 258 |
"The ENABLE_ANALYTICS setting should be set to True in deployment.", |
| 259 |
id="myapp.W001", |
| 260 |
) |
| 261 |
) |
| 262 |
return errors |
| 263 |
|
| 264 |
Given that this check will not raise a ``SystemCheckError``, the presence of |
| 265 |
the warning message in the ``stderr`` output can be asserted like so:: |
| 266 |
|
| 267 |
from io import StringIO |
| 268 |
|
| 269 |
from django.core.management import call_command |
| 270 |
from django.test import SimpleTestCase, override_settings |
| 271 |
|
| 272 |
|
| 273 |
class EnableAnalyticsDeploymentCheckTest(SimpleTestCase): |
| 274 |
@override_settings(ENABLE_ANALYTICS=None) |
| 275 |
def test_when_set_to_none(self): |
| 276 |
stderr = StringIO() |
| 277 |
call_command("check", "-t", "myapp", "--deploy", stderr=stderr) |
| 278 |
message = ( |
| 279 |
"(myapp.W001) The ENABLE_ANALYTICS setting should be set " |
| 280 |
"to True in deployment." |
| 281 |
) |
| 282 |
self.assertIn(message, stderr.getvalue()) |