checks.txt 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 be
  41. run on *all* installed apps in the project. The ``**kwargs`` argument is required
  42. for future expansion.
  43. Messages
  44. --------
  45. The function must return a list of messages. If no problems are found as a result
  46. of the check, the check function must return an empty list.
  47. The warnings and errors raised by the check method must be instances of
  48. :class:`~django.core.checks.CheckMessage`. An instance of
  49. :class:`~django.core.checks.CheckMessage` encapsulates a single reportable
  50. error or warning. It also provides context and hints applicable to the
  51. message, and a unique identifier that is used for filtering purposes.
  52. The concept is very similar to messages from the :doc:`message framework
  53. </ref/contrib/messages>` or the :doc:`logging framework </topics/logging>`.
  54. Messages are tagged with a ``level`` indicating the severity of the message.
  55. There are also shortcuts to make creating messages with common levels easier.
  56. When using these classes you can omit the ``level`` argument because it is
  57. implied by the class name.
  58. * :class:`Debug`
  59. * :class:`Info`
  60. * :class:`Warning`
  61. * :class:`Error`
  62. * :class:`Critical`
  63. Registering and labeling checks
  64. -------------------------------
  65. Lastly, your check function must be registered explicitly with system check
  66. registry. Checks should be registered in a file that's loaded when your
  67. application is loaded; for example, in the :meth:`AppConfig.ready()
  68. <django.apps.AppConfig.ready>` method.
  69. .. function:: register(*tags)(function)
  70. You can pass as many tags to ``register`` as you want in order to label your
  71. check. Tagging checks is useful since it allows you to run only a certain
  72. group of checks. For example, to register a compatibility check, you would
  73. make the following call::
  74. from django.core.checks import register, Tags
  75. @register(Tags.compatibility)
  76. def my_check(app_configs, **kwargs):
  77. # ... perform compatibility checks and collect errors
  78. return errors
  79. You can register "deployment checks" that are only relevant to a production
  80. settings file like this::
  81. @register(Tags.security, deploy=True)
  82. def my_check(app_configs, **kwargs):
  83. ...
  84. These checks will only be run if the :option:`check --deploy` option is used.
  85. You can also use ``register`` as a function rather than a decorator by
  86. passing a callable object (usually a function) as the first argument
  87. to ``register``.
  88. The code below is equivalent to the code above::
  89. def my_check(app_configs, **kwargs):
  90. ...
  91. register(my_check, Tags.security, deploy=True)
  92. .. _field-checking:
  93. Field, model, and manager checks
  94. --------------------------------
  95. In some cases, you won't need to register your check function -- you can
  96. piggyback on an existing registration.
  97. Fields, models, and model managers all implement a ``check()`` method that is
  98. already registered with the check framework. If you want to add extra checks,
  99. you can extend the implementation on the base class, perform any extra
  100. checks you need, and append any messages to those generated by the base class.
  101. It's recommended that you delegate each check to separate methods.
  102. Consider an example where you are implementing a custom field named
  103. ``RangedIntegerField``. This field adds ``min`` and ``max`` arguments to the
  104. constructor of ``IntegerField``. You may want to add a check to ensure that users
  105. provide a min value that is less than or equal to the max value. The following
  106. code snippet shows how you can implement this check::
  107. from django.core import checks
  108. from django.db import models
  109. class RangedIntegerField(models.IntegerField):
  110. def __init__(self, min=None, max=None, **kwargs):
  111. super(RangedIntegerField, self).__init__(**kwargs)
  112. self.min = min
  113. self.max = max
  114. def check(self, **kwargs):
  115. # Call the superclass
  116. errors = super(RangedIntegerField, self).check(**kwargs)
  117. # Do some custom checks and add messages to `errors`:
  118. errors.extend(self._check_min_max_values(**kwargs))
  119. # Return all errors and warnings
  120. return errors
  121. def _check_min_max_values(self, **kwargs):
  122. if (self.min is not None and
  123. self.max is not None and
  124. self.min > self.max):
  125. return [
  126. checks.Error(
  127. 'min greater than max.',
  128. hint='Decrease min or increase max.',
  129. obj=self,
  130. id='myapp.E001',
  131. )
  132. ]
  133. # When no error, return an empty list
  134. return []
  135. If you wanted to add checks to a model manager, you would take the same
  136. approach on your subclass of :class:`~django.db.models.Manager`.
  137. If you want to add a check to a model class, the approach is *almost* the same:
  138. the only difference is that the check is a classmethod, not an instance method::
  139. class MyModel(models.Model):
  140. @classmethod
  141. def check(cls, **kwargs):
  142. errors = super(MyModel, cls).check(**kwargs)
  143. # ... your own checks ...
  144. return errors
  145. Writing tests
  146. -------------
  147. Messages are comparable. That allows you to easily write tests::
  148. from django.core.checks import Error
  149. errors = checked_object.check()
  150. expected_errors = [
  151. Error(
  152. 'an error',
  153. hint='A hint.',
  154. obj=checked_object,
  155. id='myapp.E001',
  156. )
  157. ]
  158. self.assertEqual(errors, expected_errors)