2👍
I would do this way:
-
create a
messages
-like app in your project:myproject/ messages/ __init__.py
-
in your
__init__.py
file you can have function definitions:from django.contrib import messages import logging logger = logging.getLogger("messages") def debug(request, msg, *args, **kwargs): messages.debug(request, msg, *args, **kwargs) logger.debug(msg) def info(request, msg, *args, **kwargs): messages.info(request, msg, *args, **kwargs) logger.info(msg) def warning(request, msg, *args, **kwargs): messages.warning(request, msg, *args, **kwargs) logger.warning(msg) def error(request, msg, *args, **kwargs): messages.error(request, msg, *args, **kwargs) logger.error(msg)
-
define a handler for “messages” logs in your
LOGGING
variable (in thesettings
file) -
import your library instead of
django.contrib.messages
It’s a bit “boring” to write, but I think it’s general enough to be reused in several places. Of course you can take care of redefining also other functions found in django.contrib.messages
.
Unfortunately it does not make too much sense to talk about subclassing the django messages framework, since this is not defined as a class.
Hope it helps
0👍
I would suggest creating custom MESSAGE_STORAGE
based on existing storage to suit your needs. All you need to do is overload add
method. For example this one based on CookieStorage
:
import logging
from django.contrib.messages import constants, utils
from django.contrib.messages.storage.cookie import CookieStorage
logger = logging.getLogger(__name__)
class CookieLoggerStorage(CookieStorage):
def add(self, level, message, extra_tags=''):
if message and level > constants.SUCCESS: # logs WARNING and ERROR
logger.log(level, message)
super(CookieLoggerStorage, self).add(level, message, extra_tags)
In settings.py
add:
# settings.py
MESSAGE_STORAGE = "path.to.CookieLoggerStorage"
Just for clarity, messages.constants seems to be the same as logger level constants so you can almost feed logger with messages levels
django.contrib.messages.constants
DEBUG = 10
INFO = 20
SUCCESS = 25
WARNING = 30
ERROR = 40
logging constants
DEBUG 10
INFO 20
WARNING 30
ERROR 40
CRITICAL 50
NOTSET 0
- [Answered ]-Modifying User instances in Django already in database
- [Answered ]-TypeError: 'function' object has no attribute '__getitem__'; MEDIA_URL
- [Answered ]-Can't update User and UserProfile in one View?
- [Answered ]-Secure browser-based S3 uploads: signed policy doc or presigned URL?
- [Answered ]-Django "lazy query execution" principle