checks.txt 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. ======================
  2. System check framework
  3. ======================
  4. .. versionadded:: 1.7
  5. .. module:: django.core.checks
  6. The system check framework is a set of static checks for validating Django
  7. projects. It detects common problems and provides hints for how to fix them.
  8. The framework is extensible so you can easily add your own checks.
  9. Checks can be triggered explicitly via the :djadmin:`check` command. Checks are
  10. triggered implicitly before most commands, including :djadmin:`runserver` and
  11. :djadmin:`migrate`. For performance reasons, the checks are not performed if
  12. :setting:`DEBUG` is set to ``False``.
  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 register
  25. @register()
  26. def example_check(app_configs, **kwargs):
  27. errors = []
  28. # ... your check logic here
  29. return errors
  30. The check function *must* accept an ``app_configs`` argument; this argument is
  31. the list of applications that should be inspected. If None, the check must be
  32. run on *all* installed apps in the project. The ``**kwargs`` argument is required
  33. for future expansion.
  34. Messages
  35. --------
  36. The function must return a list of messages. If no problems are found as a result
  37. of the check, the check function must return an empty list.
  38. .. class:: CheckMessage(level, msg, hint, obj=None, id=None)
  39. The warnings and errors raised by the check method must be instances of
  40. :class:`~django.core.checks.CheckMessage`. An instance of
  41. :class:`~django.core.checks.CheckMessage` encapsulates a single reportable
  42. error or warning. It also provides context and hints applicable to the
  43. message, and a unique identifier that is used for filtering purposes.
  44. The concept is very similar to messages from the :doc:`message
  45. framework </ref/contrib/messages>` or the :doc:`logging framework
  46. </topics/logging>`. Messages are tagged with a ``level`` indicating the
  47. severity of the message.
  48. Constructor arguments are:
  49. ``level``
  50. The severity of the message. Use one of the
  51. predefined values: ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR``,
  52. ``CRITICAL``. If the level is greater or equal to ``ERROR``, then Django
  53. will prevent management commands from executing. Messages with
  54. level lower than ``ERROR`` (i.e. warnings) are reported to the console,
  55. but can be silenced.
  56. ``msg``
  57. A short (less than 80 characters) string describing the problem. The string
  58. should *not* contain newlines.
  59. ``hint``
  60. A single-line string providing a hint for fixing the problem. If no hint
  61. can be provided, or the hint is self-evident from the error message, a
  62. value of ``None`` can be used::
  63. Error('error message') # Will not work.
  64. Error('error message', None) # Good
  65. Error('error message', hint=None) # Better
  66. ``obj``
  67. Optional. An object providing context for the message (for example, the
  68. model where the problem was discovered). The object should be a model, field,
  69. or manager or any other object that defines ``__str__`` method (on
  70. Python 2 you need to define ``__unicode__`` method). The method is used while
  71. reporting all messages and its result precedes the message.
  72. ``id``
  73. Optional string. A unique identifier for the issue. Identifiers should
  74. follow the pattern ``applabel.X001``, where ``X`` is one of the letters
  75. ``CEWID``, indicating the message severity (``C`` for criticals,
  76. ``E`` for errors and so). The number can be allocated by the application,
  77. but should be unique within that application.
  78. There are also shortcuts to make creating messages with common levels easier.
  79. When using these methods you can omit the ``level`` argument because it is
  80. implied by the class name.
  81. .. class:: Debug(msg, hint, obj=None, id=None)
  82. .. class:: Info(msg, hint, obj=None, id=None)
  83. .. class:: Warning(msg, hint, obj=None, id=None)
  84. .. class:: Error(msg, hint, obj=None, id=None)
  85. .. class:: Critical(msg, hint, obj=None, id=None)
  86. Messages are comparable. That allows you to easily write tests::
  87. from django.core.checks import Error
  88. errors = checked_object.check()
  89. expected_errors = [
  90. Error(
  91. 'an error',
  92. hint=None,
  93. obj=checked_object,
  94. id='myapp.E001',
  95. )
  96. ]
  97. self.assertEqual(errors, expected_errors)
  98. Registering and labeling checks
  99. -------------------------------
  100. Lastly, your check function must be registered explicitly with system check
  101. registry.
  102. .. function:: register(*tags)(function)
  103. You can pass as many tags to ``register`` as you want in order to label your
  104. check. Tagging checks is useful since it allows you to run only a certain
  105. group of checks. For example, to register a compatibility check, you would
  106. make the following call::
  107. from django.core.checks import register
  108. @register('compatibility')
  109. def my_check(app_configs, **kwargs):
  110. # ... perform compatibility checks and collect errors
  111. return errors
  112. .. _field-checking:
  113. Field, Model, and Manager checks
  114. --------------------------------
  115. In some cases, you won't need to register your check function -- you can
  116. piggyback on an existing registration.
  117. Fields, models, and model managers all implement a ``check()`` method that is
  118. already registered with the check framework. If you want to add extra checks,
  119. you can extend the implementation on the base class, perform any extra
  120. checks you need, and append any messages to those generated by the base class.
  121. It's recommended the you delegate each check to a separate methods.
  122. Consider an example where you are implementing a custom field named
  123. ``RangedIntegerField``. This field adds ``min`` and ``max`` arguments to the
  124. constructor of ``IntegerField``. You may want to add a check to ensure that users
  125. provide a min value that is less than or equal to the max value. The following
  126. code snippet shows how you can implement this check::
  127. from django.core import checks
  128. from django.db import models
  129. class RangedIntegerField(models.IntegerField):
  130. def __init__(self, min=None, max=None, **kwargs):
  131. super(RangedIntegerField, self).__init__(**kwargs)
  132. self.min = min
  133. self.max = max
  134. def check(self, **kwargs):
  135. # Call the superclass
  136. errors = super(RangedIntegerField, self).check(**kwargs)
  137. # Do some custom checks and add messages to `errors`:
  138. errors.extend(self._check_min_max_values(**kwargs))
  139. # Return all errors and warnings
  140. return errors
  141. def _check_min_max_values(self, **kwargs):
  142. if (self.min is not None and
  143. self.max is not None and
  144. self.min > self.max):
  145. return [
  146. checks.Error(
  147. 'min greater than max.',
  148. hint='Decrease min or increase max.',
  149. obj=self,
  150. id='myapp.E001',
  151. )
  152. ]
  153. # When no error, return an empty list
  154. return []
  155. If you wanted to add checks to a model manager, you would take the same
  156. approach on your subclass of :class:`~django.db.models.Manager`.
  157. If you want to add a check to a model class, the approach is *almost* the same:
  158. the only difference is that the check is a classmethod, not an instance method::
  159. class MyModel(models.Model):
  160. @classmethod
  161. def check(cls, **kwargs):
  162. errors = super(MyModel, cls).check(**kwargs)
  163. # ... your own checks ...
  164. return errors