Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
3|alpha|
5Messages provide feedback to users as things happen within an application. The ``MessageMixin`` enables this feedback
6for a view.
8"""
9__author__ = "Shawn Davis <shawn@superdjango.com>"
10__maintainer__ = "Shawn Davis <shawn@superdjango.com>"
11__version__ = "1.2.0-a"
13# Imports
15from django.contrib import messages
17# Exports
19__all__ = (
20 "MessageAPIBinder",
21 "MessageAPIWrapper",
22 "MessageMixin",
23)
25# Classes
28class MessageAPIWrapper(object):
29 """Wraps the ``django.contrib.messages.api`` module to capture the current request instance for function calls."""
31 def __init__(self, request):
32 """Initialize the wrapper.
34 :param request: The current HTTPRequest instance.
36 """
37 self.request = request
39 def debug(self, message):
40 messages.debug(self.request, message)
42 def error(self, message):
43 messages.error(self.request, message)
45 def info(self, message):
46 messages.info(self.request, message)
48 def success(self, message):
49 messages.success(self.request, message)
51 def warning(self, message):
52 # noinspection PyUnresolvedReferences
53 messages.warning(self.request, message)
56class MessageAPIBinder(object):
57 """Binds the ``MessageAPIWrapper`` to a view."""
59 def __get__(self, instance, owner):
60 return MessageAPIWrapper(instance.request)
62# Mixins
65class MessageMixin(object):
66 """Add a ``messages``` attribute on the view instance that wraps ``django.contrib.messages``.
68 Many HTML/CSS frameworks such as Twitter Bootstrap or UIKit have styles for ``info``, ``success``, and
69 ``warning``, but use ``danger`` for the equivalent of ``error``. You can address this by adding the following to
70 your ``settings.py`` file:
72 .. code-block:: python
74 from django.contrib import messages
76 # Map "error" to "danger" for Bootstrap/UIKit alerts.
77 from django.contrib.messages import constants as messages
78 MESSAGE_TAGS = {
79 messages.ERROR: "danger",
80 }
82 See https://docs.djangoproject.com/en/stable/ref/contrib/messages/
84 """
85 messages = MessageAPIBinder()