Django:在显示消息之前先删除消息 [英] Django: Remove message before they are displayed

查看:86
本文介绍了Django:在显示消息之前先删除消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题听起来很奇怪,但是请让我自己解释一下.

I know this question sounds weird, but please, let me explain myself.

我正在使用装饰器来使消息持久化,直到用户实际将其消除为止(例如堆栈溢出消息的行为).因此,问题在于,该消息是在用户注销之前添加的,因此该消息在用户注销后立即显示.我想知道在注销视图中删除消息的最佳方法是什么.我已经考虑过两种方法来做到这一点,并且想知道是否有人可以想到更好的方法.

I'm using a decorator to make a message persist until the user actually dismisses it (like the behavior of stack overflow's messages). The problem is, as a result of this, the message gets added before the user signs out, and so the message gets displayed right after the user logs out. I'm wondering what the best way to remove the message in the logout view is. I've thought of two ways to do this, and am wondering if anyone can think of a better one.

我目前对此很满意:

storage = messages.get_messages(request)
storage.used = True

对此:

storage = messages.get_messages(request)
del storage._loaded_messages[0]

对我来说,第二种方法似乎更明确,尽管它比较丑陋:我的意图是删除当前加载的消息,这很清楚.第一种方法采用了清除消息的一种副作用,但是至少不依赖于dunder变量……你们怎么看?

To me the second way seems more explicit, even though it is uglier: my intention is to remove the currently loaded messages and this makes that clear. The first way employs a means by which the messages will be cleared as a side effect ... but at least it doesn't rely upon a dunder variable ... what do you guys think?

推荐答案

为了解决问题,我将使用的方法标记为答案".感谢那些发表评论的人.

For the sake of resolution I'm going to mark the method I went with as "The Answer". Thanks to those who commented.

我同意了:

storage = messages.get_messages(request)
storage.used = True

因为它看起来更干净,更易于测试并且符合项目其余部分的常规做法.

Because it seemed cleaner, was easier to test, and conformed with the general practices of the rest of the project.

这篇关于Django:在显示消息之前先删除消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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