checks.txt 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. ======================
  2. System check framework
  3. ======================
  4. .. module:: django.core.checks
  5. The system check framework is a set of static checks for validating Django
  6. projects. It detects common problems and provides hints for how to fix them.
  7. The framework is extensible so you can easily add your own checks.
  8. Checks can be triggered explicitly via the :djadmin:`check` command. Checks are
  9. triggered implicitly before most commands, including :djadmin:`runserver` and
  10. :djadmin:`migrate`. For performance reasons, checks are not run as part of the
  11. WSGI stack that is used in deployment. If you need to run system checks on your
  12. deployment server, trigger them explicitly using :djadmin:`check`.
  13. Serious errors will prevent Django commands (such as :djadmin:`runserver`) from
  14. running at all. Minor problems are reported to the console. If you have inspected
  15. the cause of a warning and are happy to ignore it, you can hide specific warnings
  16. using the :setting:`SILENCED_SYSTEM_CHECKS` setting in your project settings file.
  17. A full list of all checks that can be raised by Django can be found in the
  18. :doc:`System check reference </ref/checks>`.
  19. Writing your own checks
  20. =======================
  21. The framework is flexible and allows you to write functions that perform
  22. any other kind of check you may require. The following is an example stub
  23. check function::
  24. from django.core.checks import Error, register
  25. @register()
  26. def example_check(app_configs, **kwargs):
  27. errors = []
  28. # ... your check logic here
  29. if check_failed:
  30. errors.append(
  31. Error(
  32. 'an error',
  33. hint='A hint.',
  34. obj=checked_object,
  35. id='myapp.E001',
  36. )
  37. )
  38. return errors
  39. The check function *must* accept an ``app_configs`` argument; this argument is
  40. the list of applications that should be inspected. If ``None``, the check must
  41. be run on *all* installed apps in the project.
  42. The check will receive a ``databases`` keyword argument. This is a list of
  43. database aliases whose connections may be used to inspect database level
  44. configuration. If ``databases`` is ``None``, the check must not use any
  45. database connections.
  46. The ``**kwargs`` argument is required for future expansion.
  47. Messages
  48. --------
  49. The function must return a list of messages. If no problems are found as a result
  50. of the check, the check function must return an empty list.
  51. The warnings and errors raised by the check method must be instances of
  52. :class:`~django.core.checks.CheckMessage`. An instance of
  53. :class:`~django.core.checks.CheckMessage` encapsulates a single reportable
  54. error or warning. It also provides context and hints applicable to the
  55. message, and a unique identifier that is used for filtering purposes.
  56. The concept is very similar to messages from the :doc:`message framework
  57. </ref/contrib/messages>` or the :doc:`logging framework </topics/logging>`.
  58. Messages are tagged with a ``level`` indicating the severity of the message.
  59. There are also shortcuts to make creating messages with common levels easier.
  60. When using these classes you can omit the ``level`` argument because it is
  61. implied by the class name.
  62. * :class:`Debug`
  63. * :class:`Info`
  64. * :class:`Warning`
  65. * :class:`Error`
  66. * :class:`Critical`
  67. .. _registering-labeling-checks:
  68. Registering and labeling checks
  69. -------------------------------
  70. Lastly, your check function must be registered explicitly with system check
  71. registry. Checks should be registered in a file that's loaded when your
  72. application is loaded; for example, in the :meth:`AppConfig.ready()
  73. <django.apps.AppConfig.ready>` method.
  74. .. function:: register(*tags)(function)
  75. You can pass as many tags to ``register`` as you want in order to label your
  76. check. Tagging checks is useful since it allows you to run only a certain
  77. group of checks. For example, to register a compatibility check, you would
  78. make the following call::
  79. from django.core.checks import register, Tags
  80. @register(Tags.compatibility)
  81. def my_check(app_configs, **kwargs):
  82. # ... perform compatibility checks and collect errors
  83. return errors
  84. You can register "deployment checks" that are only relevant to a production
  85. settings file like this::
  86. @register(Tags.security, deploy=True)
  87. def my_check(app_configs, **kwargs):
  88. ...
  89. These checks will only be run if the :option:`check --deploy` option is used.
  90. You can also use ``register`` as a function rather than a decorator by
  91. passing a callable object (usually a function) as the first argument
  92. to ``register``.
  93. The code below is equivalent to the code above::
  94. def my_check(app_configs, **kwargs):
  95. ...
  96. register(my_check, Tags.security, deploy=True)
  97. .. _field-checking:
  98. Field, model, manager, migration, and database checks
  99. -----------------------------------------------------
  100. In some cases, you won't need to register your check function -- you can
  101. piggyback on an existing registration.
  102. Fields, models, model managers, migrations, and database backends all implement
  103. a ``check()`` method that is already registered with the check framework. If
  104. you want to add extra checks, you can extend the implementation on the base
  105. class, perform any extra checks you need, and append any messages to those
  106. generated by the base class. It's recommended that you delegate each check to
  107. separate methods.
  108. Consider an example where you are implementing a custom field named
  109. ``RangedIntegerField``. This field adds ``min`` and ``max`` arguments to the
  110. constructor of ``IntegerField``. You may want to add a check to ensure that users
  111. provide a min value that is less than or equal to the max value. The following
  112. code snippet shows how you can implement this check::
  113. from django.core import checks
  114. from django.db import models
  115. class RangedIntegerField(models.IntegerField):
  116. def __init__(self, min=None, max=None, **kwargs):
  117. super().__init__(**kwargs)
  118. self.min = min
  119. self.max = max
  120. def check(self, **kwargs):
  121. # Call the superclass
  122. errors = super().check(**kwargs)
  123. # Do some custom checks and add messages to `errors`:
  124. errors.extend(self._check_min_max_values(**kwargs))
  125. # Return all errors and warnings
  126. return errors
  127. def _check_min_max_values(self, **kwargs):
  128. if (self.min is not None and
  129. self.max is not None and
  130. self.min > self.max):
  131. return [
  132. checks.Error(
  133. 'min greater than max.',
  134. hint='Decrease min or increase max.',
  135. obj=self,
  136. id='myapp.E001',
  137. )
  138. ]
  139. # When no error, return an empty list
  140. return []
  141. If you wanted to add checks to a model manager, you would take the same
  142. approach on your subclass of :class:`~django.db.models.Manager`.
  143. If you want to add a check to a model class, the approach is *almost* the same:
  144. the only difference is that the check is a classmethod, not an instance method::
  145. class MyModel(models.Model):
  146. @classmethod
  147. def check(cls, **kwargs):
  148. errors = super().check(**kwargs)
  149. # ... your own checks ...
  150. return errors
  151. .. versionchanged:: 4.2
  152. Migration checks were added.
  153. Writing tests
  154. -------------
  155. Messages are comparable. That allows you to easily write tests::
  156. from django.core.checks import Error
  157. errors = checked_object.check()
  158. expected_errors = [
  159. Error(
  160. 'an error',
  161. hint='A hint.',
  162. obj=checked_object,
  163. id='myapp.E001',
  164. )
  165. ]
  166. self.assertEqual(errors, expected_errors)