删除所有django.contrib.messages [英] Delete all django.contrib.messages

查看:216
本文介绍了删除所有django.contrib.messages的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近意识到Django Web应用程序中的一个模块正在使用django.contrib.messages.但是,模板的上下文处理器未添加django.contrib.messages.context_processors.messages处理器.

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.

我担心,当我将其推送到生产环境时,用户会看到生成它们的所有页面的所有旧消息.有没有办法从django shell为所有用户清除这些消息?

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?

推荐答案

将为那些会话中已经包含该消息的用户显示消息.因此,您有几种选择可以做.

Messages will be shown for those users whose sessions already contain the message. So you have several options to do.

  1. 如果您使用的是默认设置,并且会话数据存储在数据库表中,则可以遍历活动会话并检查是否为它们存储了任何消息.

  1. 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 

  • 如果您不使用默认设置并将会话数据存储在其他位置(Redis?),或者您不想采用以前的方式,则可以完全删除所有会话.这样会有一个缺点,那就是您的用户将被注销(可能是可以接受的结果)

  • 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]
    

  • 或使用首选的django-ish方式删除它们:

    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.

    1. 只需删除中间件并完全释放消息,如果不需要,请勿使用.

    这篇关于删除所有django.contrib.messages的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆