Django Messages Framework

Source: Internet
Author: User
Tags sessionstorage

I. INTRODUCTION

In Web applications, you often need to display a notification message (also called a "flash message") to the user after processing the form or other type of user input

For this feature, Django provides cookies and session-based messages, both anonymous and authenticated users.

Its message framework allows you to temporarily store messages in the request and extract them and display them in the next request (usually the next request). Each message comes with a specific level label, indicating its priority (for example, info,warning , or error)

two. Enabling the message framework  

The implementation of the message framework is through a middleware class and corresponding context processor.

The default settings.py created by django-admin startproject already contains all the settings required to enable the Messaging framework feature:

  • The ' django.contrib.messages 'in Installed_apps .

  • middleware _classes   Django.contrib.sessions.middleware.SessionMiddleware '   and .

    default back-end storage   dependency sessions. so middleware_classes   must enable sessionmiddleware   and appears in the TT class= "docutils literal" >messagemiddleware before  .

  • templates   settings defined in djangotemplates   ' context_processors '   options include ' django.contrib.messages.context_processors.messages ' .

If you do not want to use the message frame, you can delete the ' django.contrib.messages 'in the Installed_apps , themiddleware_classes in the Messages context Processo in Messagemiddleware and TEMPLATES

2.1 Configuring the message Framework engine

  

The message framework can use different background storage for temporary messages.

Django provides three built-in storage classes in django.contrib.messages :

Class storage.session. Sessionstorage

This class stores all messages in the requested session. Therefore, it requires the contrib.sessions app to be enabled for Django.

Class Storage.cookie. Cookiestorage

This class stores the message data in a cookie (already signed with a secure hash to prevent tampering) to pass the message between requests. If the cookie data size will exceed 2048 bytes, the old message will be discarded.

Class Storage.fallback. Fallbackstorage

This class first uses Cookiestorage, and sessionstorageis used if the message is not plugged into a cookie. It also requires a Django-enabled contrib.sessions application.

This behavior avoids writing sessions every time. in general, the performance it provides should be the best.

fallbackstorage is the default storage class. If it does not suit your needs, you can select another storage class by setting Message_storage for its full import path, for example:

' Django.contrib.messages.storage.cookie.CookieStorage '

3.3 Message Level

  the level of the message frame is configurable, similar to the Python logging module. The level of messages allows you to group by type so that they can be filtered or displayed in different views and templates

The built-in levels of the django.contrib.messages import are:

Constant Purpose
debug development-related messages that'll be ignored (or removed) in a production deployment
info Informational messages for the user
success An action is successful, e.g." Your profile was updated Successfully "
warning A failure did Not occur but may is imminent
error An action was , not  successful or some other failure occurred

the message_level setting can be used to change the minimum level of a record (it can also be modified in each request). messages smaller than this level will be ignored.

To modify the default label for the message level, set message_tags to the dictionary that contains the level you want to modify

 from Import  = {    ',    'critical',} 
3.3 Using in views and templates
Add_message (Request, level, message, extra_tags=", Fail_silently=false)

Cases

New Message

 from Import  'Hello world. ')

There are several quick ways to provide a standard way to add messages with common tags (these usually represent the HTML type of the message)

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.')
3.4 Displaying messages

get_messages (Request)

in your template , use the following as follows:

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

The above is just a simple example to use, see more detailed documentation please refer to https://docs.djangoproject.com/en/1.10/ref/contrib/messages/

In the production use we can integrate it into a module for easy invocation, combined with the front-end display when there is error or other information when the browser can alert messages

Cases

 fromDjango.contrib.messagesImportConstants as Message_constantsmessage_level=message_constants.infotemplates= [    {        'Backend':'django.template.backends.django.DjangoTemplates',        'DIRS': [Os.path.join (Base_dir,"Templates")],        'App_dirs': True,'OPTIONS': {            'context_processors': [                'Django.template.context_processors.debug',                'django.template.context_processors.request',                'Django.contrib.auth.context_processors.auth',                'django.contrib.messages.context_processors.messages',            ],        },    },]
Settings
#!/usr/bin/env python#-*-coding:utf-8-*- fromDjango.contribImportMessagesdefFlash (Request, title, text, level='Info'):    """send a message using the Django message system. """Level_map= {        'Info': Messages.info,'Debug': Messages. DEBUG,'Success': Messages. SUCCESS,'Warning': Messages. WARNING,'Error': Messages. ERROR} Level=Level_map[level] Messages.add_message (request, level, text, Extra_tags=title)return 'OK'
Message Method
{% If messages%}<Script>    {%  formsginchMessages%} alert ('{{Msg.message}}'); {%endfor%}</Script>{% endif%}
front-end display

Views call

result = XXXXX      if  result:         Flash (Request,"success" " Success!  ")      Else:         Flash (Request,"Error  ",  ".... ")

Django Messages Framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.