django Message Framework message Use Detailed Explanation

  • 2021-07-24 11:21:21
  • OfStack

Preface

In web applications, we often need to display a notification message to users after processing forms or other types of user input.

For this requirement, Django provides an Cookie or session-based messaging framework, messages, for both anonymous and authenticated users. This message framework allows you to temporarily store messages in a request, extract them in the next request (usually the next request) and display them. Each message has a specific level tag indicating its priority (for example, info, warning, or error).

1. Enable the message framework

The implementation of messages message framework of Django relies on messages middleware and corresponding context processor.

When the project was created with the django-admin startproject xxx command, all the settings required for the message framework functionality were turned on by default in settings. py:

'django. contrib. messages' registered in INSTALLED_APPS. Add 'django. contrib. sessions. middleware. SessionMiddleware' and 'django. contrib. messages. middleware. MessageMiddleware' to MIDDLEWARE. The messages framework of Django defaults to the storage backend of sessions. So the Session middleware must be enabled and appear before the Message middleware. The DjangoTemplates option in the TEMPLATES setting contains the 'context_processors' configuration entry that contains' django. contrib. messages. context_processors. messages '.

2. Configure the message engine

Usually we just use the default, so we can skip this section, but if we really need it, we can also configure:

1. Storage backend

Django provides three built-in message store backends:

class storage.session.SessionStorage class storage.cookie.CookieStorage class storage.fallback.FallbackStorage

FallbackStorage is the default storage backend. If it is not suitable for your needs, you can choose another storage backend by setting MESSAGE_STORAGE, for example:

MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

2. Message level

The level of the message framework is configurable, similar to the logging module of Python

There are several message levels built into Django:

级别 说明
DEBUG 将在生产部署中忽略(或删除)的与开发相关的消息
INFO 普通提示信息
SUCCESS 成功信息
WARNING 警告信息
ERROR 已经发生的错误信息

3. Message style

Usually, in the front-end HTML page, we want to add different CSS styles to different levels of messages, such as yellow warning, red error and so on.

Django provides us with a default style correspondence:

级别 样式
DEBUG debug
INFO info
SUCCESS success
WARNING warning
ERROR error

That is to say, SUCCESS level messages will be given an success style class at the front end.

To modify the default style of the message level, set MESSAGE_TAGS, as shown in the following example:.


from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
  messages.INFO: '',
  50: 'critical',
}

3. Using a message framework

1. Add a message

Method prototype: add_message(request, level, message, extra_tags='', fail_silently=False)[source]

Add 1 message:


from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')

Provide request object request (just use it directly), message level and message content string.

Or use the following shortcut


messages.debug(request, '%s SQL statements were executed.' % count)
messages.info(request, 'Three credits remain in your account.')
messages.success(request, 'Profile details updated.')
messages.warning(request, 'Your account expires in three days.')
messages.error(request, 'Document deleted.')

2. Display messages

Method prototype: get_messages (request) [source]

In your template file, use it like this:


{% if messages %}
<ul class="messages">
  {% for message in messages %}
  <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
  {% endfor %}
</ul>
{% endif %}

Related notes:

Judging whether there is a message through if; messages is a list that must be looped with the for tag; Even if you know there is only one message, iterate through the messages list, otherwise the message from the previous request will not be cleared in the next request. You can get the CSS style of each message through message. tags

There is one DEFAULT_MESSAGE_LEVELS variable that maps message level names to their numeric values:


{% if messages %}
<ul class="messages">
  {% for message in messages %}
  <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
    {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
    {{ message }}
  </li>
  {% endfor %}
</ul>
{% endif %}

Description:

You can get the level value of the current message through message. level; Compare it with DEFAULT_MESSAGE_LEVELS. ERROR; If 1, it means that the current message level is ERROR and needs to be displayed on the page.

Outside the template, such as in the view, you can use the get_messages () method to get the message:


from django.contrib.messages import get_messages

storage = get_messages(request)
for message in storage:
  do_something_with_the_message(message)

Description:

get_messages () returns one instance of the storage backend. Loop around this instance to get each message

For every 1 message instance, it contains the following properties, which can be called in the template or view:

message: The actual content text of the message. Do not use message. message, direct message. level: Message level, 1 integer. tags: A string composed of all the tags of the message (extra_tags and tags) separated by spaces. extra_tags: A string composed of custom tags for the message and separated by spaces. It defaults to null. level_tag: The CSS string corresponding to the current message level, described earlier.

3. Customize the message level

The message level is only an integer constant, so you can define your own level constants, such as:


CRITICAL = 50

def my_view(request):
  messages.add_message(request, CRITICAL, 'A serious error occurred.')

When customizing message levels, care should be taken to avoid overwriting existing levels. The values of the built-in level are:

级别 对应整数值
DEBUG 10
INFO 20
SUCCESS 25
WARNING 30
ERROR 40

If you need to use custom levels in HTML or CSS, you need to provide the corresponding mapping relationship through MESSAGE_TAGS setting.

4. Customize the minimum record level per request

The minimum record level can be set for each request using the set_level () method, as follows:


from django.contrib import messages

#  Modify the minimum level to DEBUG
messages.set_level(request, messages.DEBUG)
messages.debug(request, 'Test message...')

#  In addition 1 The minimum level of modification in the views is WARNING
messages.set_level(request, messages.WARNING)
messages.success(request, 'Your profile was updated.') #  Ignored, not recorded 
messages.warning(request, 'Your account is about to expire.') #  Record 

#  Restore the minimum level to the default value 
messages.set_level(request, None)
set_level() Method receive request Be the first 1 Parameter, the message level is the first 2 Parameter. 

Similarly, the current valid record level can be obtained using the get_level () method:


from django.contrib import messages
current_level = messages.get_level(request)

5. Adding additional message CSS styles

To add a custom message CSS style, you can use the extra_tags parameter:


messages.add_message(request, messages.INFO, 'Over 9000!', extra_tags='dragonball')
messages.error(request, 'Email box full', extra_tags='email')

4. Message expiration mechanism

By default, if the iterator containing the message completes the iteration, all messages in the current request are deleted.

If you don't want to do this and want to keep these messages, you need to explicitly specify the used parameter as False, as follows:


from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')
0

Related articles: