Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

exceptions.py 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """
  2. Global Django exception and warning classes.
  3. """
  4. class FieldDoesNotExist(Exception):
  5. """The requested model field does not exist"""
  6. pass
  7. class AppRegistryNotReady(Exception):
  8. """The django.apps registry is not populated yet"""
  9. pass
  10. class ObjectDoesNotExist(Exception):
  11. """The requested object does not exist"""
  12. silent_variable_failure = True
  13. class MultipleObjectsReturned(Exception):
  14. """The query returned multiple objects when only one was expected."""
  15. pass
  16. class SuspiciousOperation(Exception):
  17. """The user did something suspicious"""
  18. class SuspiciousMultipartForm(SuspiciousOperation):
  19. """Suspect MIME request in multipart form data"""
  20. pass
  21. class SuspiciousFileOperation(SuspiciousOperation):
  22. """A Suspicious filesystem operation was attempted"""
  23. pass
  24. class DisallowedHost(SuspiciousOperation):
  25. """HTTP_HOST header contains invalid value"""
  26. pass
  27. class DisallowedRedirect(SuspiciousOperation):
  28. """Redirect to scheme not in allowed list"""
  29. pass
  30. class TooManyFieldsSent(SuspiciousOperation):
  31. """
  32. The number of fields in a GET or POST request exceeded
  33. settings.DATA_UPLOAD_MAX_NUMBER_FIELDS.
  34. """
  35. pass
  36. class RequestDataTooBig(SuspiciousOperation):
  37. """
  38. The size of the request (excluding any file uploads) exceeded
  39. settings.DATA_UPLOAD_MAX_MEMORY_SIZE.
  40. """
  41. pass
  42. class PermissionDenied(Exception):
  43. """The user did not have permission to do that"""
  44. pass
  45. class ViewDoesNotExist(Exception):
  46. """The requested view does not exist"""
  47. pass
  48. class MiddlewareNotUsed(Exception):
  49. """This middleware is not used in this server configuration"""
  50. pass
  51. class ImproperlyConfigured(Exception):
  52. """Django is somehow improperly configured"""
  53. pass
  54. class FieldError(Exception):
  55. """Some kind of problem with a model field."""
  56. pass
  57. NON_FIELD_ERRORS = '__all__'
  58. class ValidationError(Exception):
  59. """An error while validating data."""
  60. def __init__(self, message, code=None, params=None):
  61. """
  62. The `message` argument can be a single error, a list of errors, or a
  63. dictionary that maps field names to lists of errors. What we define as
  64. an "error" can be either a simple string or an instance of
  65. ValidationError with its message attribute set, and what we define as
  66. list or dictionary can be an actual `list` or `dict` or an instance
  67. of ValidationError with its `error_list` or `error_dict` attribute set.
  68. """
  69. super().__init__(message, code, params)
  70. if isinstance(message, ValidationError):
  71. if hasattr(message, 'error_dict'):
  72. message = message.error_dict
  73. elif not hasattr(message, 'message'):
  74. message = message.error_list
  75. else:
  76. message, code, params = message.message, message.code, message.params
  77. if isinstance(message, dict):
  78. self.error_dict = {}
  79. for field, messages in message.items():
  80. if not isinstance(messages, ValidationError):
  81. messages = ValidationError(messages)
  82. self.error_dict[field] = messages.error_list
  83. elif isinstance(message, list):
  84. self.error_list = []
  85. for message in message:
  86. # Normalize plain strings to instances of ValidationError.
  87. if not isinstance(message, ValidationError):
  88. message = ValidationError(message)
  89. if hasattr(message, 'error_dict'):
  90. self.error_list.extend(sum(message.error_dict.values(), []))
  91. else:
  92. self.error_list.extend(message.error_list)
  93. else:
  94. self.message = message
  95. self.code = code
  96. self.params = params
  97. self.error_list = [self]
  98. @property
  99. def message_dict(self):
  100. # Trigger an AttributeError if this ValidationError
  101. # doesn't have an error_dict.
  102. getattr(self, 'error_dict')
  103. return dict(self)
  104. @property
  105. def messages(self):
  106. if hasattr(self, 'error_dict'):
  107. return sum(dict(self).values(), [])
  108. return list(self)
  109. def update_error_dict(self, error_dict):
  110. if hasattr(self, 'error_dict'):
  111. for field, error_list in self.error_dict.items():
  112. error_dict.setdefault(field, []).extend(error_list)
  113. else:
  114. error_dict.setdefault(NON_FIELD_ERRORS, []).extend(self.error_list)
  115. return error_dict
  116. def __iter__(self):
  117. if hasattr(self, 'error_dict'):
  118. for field, errors in self.error_dict.items():
  119. yield field, list(ValidationError(errors))
  120. else:
  121. for error in self.error_list:
  122. message = error.message
  123. if error.params:
  124. message %= error.params
  125. yield str(message)
  126. def __str__(self):
  127. if hasattr(self, 'error_dict'):
  128. return repr(dict(self))
  129. return repr(list(self))
  130. def __repr__(self):
  131. return 'ValidationError(%s)' % self
  132. class EmptyResultSet(Exception):
  133. """A database query predicate is impossible."""
  134. pass