删除/清除django.contrib.messages [英] Deleting/Clearing django.contrib.messages
问题描述
我想有条件清除 django.contrib.messages
。这两个问题中讨论的解决方案均无效:
I want to conditionally clear django.contrib.messages
. None of the solutions discussed in these two questions work:
删除所有django.contrib.messages
Django:在显示消息之前先删除消息
关于如何清除消息的任何建议?我正在使用Django 1.10
Any suggestions on how I can clear the messages? I am using django 1.10
代码:
messages = get_messages(request)
for msg in messages:
pass
for msg in messages._loaded:
del msg
for msg in messages._queued_messages:
del msg
推荐答案
您需要遍历当前集合中的消息从 get_messages方法中检索到的消息数量。您可以在设置新消息之前清除消息的任何地方或仅清除所有消息的地方使用此代码。
You need to iterate through the messages for your current set of messages as retrieved from the 'get_messages' method. You can use this code anywhere you want to clear the messages before setting new ones or where you want to simply clear all messages.
system_messages = messages.get_messages(request)
for message in system_messages:
# This iteration is necessary
pass
注:如果您不想清除消息,则将system_messages.used标志设置为'False',因为标记为在迭代存储实例时将其清除(并在以下情况时清除)响应已处理)。
参考: https://docs.djangoproject.com/en/ 3.0 / ref / contrib / messages
Note: If you do not want to clear messages, then set the system_messages.used flag to 'False' as the messages are marked to be cleared when the storage instance is iterated (and cleared when the response is processed). Reference: https://docs.djangoproject.com/en/3.0/ref/contrib/messages
这篇关于删除/清除django.contrib.messages的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!