Django消息框架和login_required [英] Django message framework and login_required

查看:248
本文介绍了Django消息框架和login_required的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django Message Framework向用户显示消息以及我的一个视图中的 @login_required 装饰器。因此,如果用户尝试访问某个视图而不登录,则会被踢到登录页面。我将如何向登录页面添加错误消息,说为了做...你必须登录。我不能像你通常那样在视图中添加它,因为未登录的用户永远不会到达。

I'm using the Django Message Framework to show messages to users as well as the @login_required decorator on one of my views. So if a user tries to access a certain view without being logged in, they get kicked to the login page. How would I go about adding an error message to the login page saying "In order to do ... you must be logged in". I can't add it in the view like you normally would because the non-logged in user would never get to there.

推荐答案

没有什么明显的方法唯一需要注意的事情是编写自己的装饰器版本,在重定向之前将一个消息放入会话中,然后获取登录模板以显示会话中的消息。

There's not any obvious way. The only thing that springs to mind is to write your own version of the decorator that puts a message into the session before redirecting, then get the login template to display the message from the session.

您需要使用 django.contrib.auth.decorators 中的代码,特别是 user_passes_test 函数 - 添加消息的位将不得不在之前返回HttpResponseRedirect

You'd need to use the code in django.contrib.auth.decorators, in particular the user_passes_test function - the bit to add the message would have to go before return HttpResponseRedirect.

这篇关于Django消息框架和login_required的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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