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.

middleware.py 986B

1234567891011121314151617181920212223242526
  1. from django.conf import settings
  2. from django.contrib.messages.storage import default_storage
  3. from django.utils.deprecation import MiddlewareMixin
  4. class MessageMiddleware(MiddlewareMixin):
  5. """
  6. Middleware that handles temporary messages.
  7. """
  8. def process_request(self, request):
  9. request._messages = default_storage(request)
  10. def process_response(self, request, response):
  11. """
  12. Update the storage backend (i.e., save the messages).
  13. Raise ValueError if not all messages could be stored and DEBUG is True.
  14. """
  15. # A higher middleware layer may return a request which does not contain
  16. # messages storage, so make no assumption that it will be there.
  17. if hasattr(request, '_messages'):
  18. unstored_messages = request._messages.update(response)
  19. if unstored_messages and settings.DEBUG:
  20. raise ValueError('Not all temporary messages could be stored.')
  21. return response