# MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
# MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
INSTALLED_APPS = [
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
'django.contrib.messages', # 設定
'django.contrib.staticfiles',
"web.apps.WebConfig"
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', # 中介軟體
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'utils.md.AuthMiddleware'
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
from django.contrib import messages
messages.add_message(reqeust, messages.SUCCESS, "刪除成功1")
messages.add_message(reqeust, messages.ERROR, "操作失敗")
from django.contrib.messages.api import get_messages
messages = get_messages(request)
for msg in messages:
print(msg)
<ul>
{% for message in messages %}
<li>{{ message.tags }} {{ message }}</li>
{% endfor %}
</ul>
from django.contrib import messages
messages.add_message(reqeust, messages.SUCCESS, "刪除成功1")
我們根據django的生命週期, 從Middleware入手,
【設定】中介軟體process_request載入
【設定】在檢視函數中往message中寫入值(記憶體)
【設定】中介軟體process_response,將記憶體中新增的資料寫入到資料來源
【新頁面】中介軟體process_request載入
【新頁面】在檢視函數或模板中讀取message中的資訊(老的資料來源載入的+新增的)
【設定】中介軟體process_response
used = True,則只儲存新增部分。
added_new = True,老的資料來源載入的+新增的都重新儲存到資料來源。
本文來自部落格園,作者:{Max},僅供學習和參考