黑客Django管理员,挂钩登录/注销 [英] Hacking Django Admin, hooks for login/logout

查看:122
本文介绍了黑客Django管理员,挂钩登录/注销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

如何添加钩子到Django管理员,这样我可以在用户登录时执行一个功能?

更新:自Django 1.3以来,此方法已过时,请参见 Tommy的answer ,以便使用信号。



我也在寻找一个答案,最后以另一种方式。您可以使用自己的视图登录和注销,执行一些操作,然后调用auth视图。登录时:

  def login(request,* args,** kwargs):
from django.contrib.auth .forms import AuthenticationForm
如果request.method =='POST':
form = AuthenticationForm(data = request.POST)
如果form.is_valid():
#登录成功
do_something()
from django.contrib.auth.views import login as authlogin
return authlogin(request,* args,** kwargs)

注销:

  def logout ,* args,** kwargs):
do_something()
from django.contrib.auth.views import logout as authlogout
return authlogout(request,* args,** kwargs)

您可以在自定义视图中进行任何处理,代替do_something占位符,例如发出信号,记录登录和注销时间等。



最后,不要忘记更新您的 urls.py 指向您的自定义视图。



我不知道自定义的auth后端可以如何处理注销事件,因为我最终放弃了,并尝试这样做。此外,这种方法的优点是可以使用请求对象,而不仅仅是用户。


How do I add hooks to the Django Admin, such that I can execute a function when the user logs in or out?

解决方案

Update: This method is obsolete since Django 1.3, see Tommy's answer below for using signals.

I was also looking for an answer to this and ended up going another way. You can use your own views for login and logout, which perform some action and then call the auth views. For login:

def login(request, *args, **kwargs):
    from django.contrib.auth.forms import AuthenticationForm
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            # login successful
            do_something()
    from django.contrib.auth.views import login as authlogin
    return authlogin(request, *args, **kwargs)

And for logout:

def logout(request, *args, **kwargs):
    do_something() 
    from django.contrib.auth.views import logout as authlogout
    return authlogout(request, *args, **kwargs)

You can do whatever processing you like in your custom views in place of the do_something placeholders, such as emitting signals, logging log-in and log-out times, etc.

Finally, don't forget to update your urls.py to point to your custom views.

I'm not sure how a custom auth backend can handle logout events, as i eventually gave up on that and tried this instead. Additionally, this approach has the advantage of making available the request object instead of just the user.

这篇关于黑客Django管理员,挂钩登录/注销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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