问题
I recently realized that a module in our Django web app was using django.contrib.messages. However, the template's context processor did not have the django.contrib.messages.context_processors.messages
processor added.
I'm worried that when I push this to production, users will see all their old messages for all pages that had generated them. Is there a way to clear these messages for all users from the django shell
?
回答1:
Messages will be shown for those users whose sessions already contain the message. So you have several options to do.
In case you're using the default settings and session data are stored in a database table, you can iterate through active sessions and check to see if there's any message stored for them.
from django.contrib.sessions.models import Session for s in Session.objects.all(): decoded_data_dict = s.get_decoded() # Now you look for messages in the dict, delete them (del dict[key]) and save the session
In case you don't use the default settings and store session data elsewhere (Redis?), or you don't want to go the previous way, you can drop all sessions altogether. This will have a drawback, that your users will be logged out (which might be an acceptable consequence)
You can do this per each request of your users, you need to delete session's messages without deleting all the session object. Something like the following would do:
for key in request.session.keys(): del request.session[key]
or remove them using the prefered django-ish way:
storage = messages.get_messages(request)
storage.used = True
The drawback of this method is that you have to only remove messages, if its the first visit of an already logged in user, and then don't do it again, since you want your users to be able to view their messages from now on.
- Just remove the middleware and let go of messages altogether, if you don't need it, don't use it.
回答2:
Messages are usually stored either in sessions or cookies (check your storage backend). You can clear them from there, but they'll be cleared when sessions/cookies are normally cleared anyway (on user logout at the worst).
If you want to be sure these messages don't display, you can disable the messaging framework:
If you don’t want to use messages, you can remove 'django.contrib.messages' from your INSTALLED_APPS, the MessageMiddleware line from MIDDLEWARE, and the messages context processor from TEMPLATES.
来源:https://stackoverflow.com/questions/39518310/delete-all-django-contrib-messages