LoginRequiredMixin的反义词是什么,如何拒绝对登录用户的访问?

时间:2016-07-08 20:17:57

标签: python django

例如,如果用户已经登录,我是否不想授予“注册”视图的访问权限?

我在每个视图的顶部使用它,它工作正常:

setContent()

但也许有一个装饰者混合,我想知道是否有更好的方法来做到这一点?谢谢!

3 个答案:

答案 0 :(得分:3)

Django有一个user_passes_test装饰器,我认为你需要它。装饰器将一个函数(带有其他可选的函数)作为参数。

您可以编写此函数来重定向尝试访问该视图的所有登录用户:

from django.contrib.auth.decorators import user_passes_test

def not_logged_in(user):
    return not user.is_authenticated()

@user_passes_test(not_logged_in)
def my_view(request, *args, **kwargs):
     # your code

请务必使用method_decorator将此装饰器应用于get方法。

答案 1 :(得分:0)

您可以创建自定义“LogoutRequiredMixin”:

class LogoutRequiredMixin(View):

    def dispatch(self, *args, **kwargs):
        if request.user.is_authenticated():
            return HttpResponseRedirect('/')
        return super(LogoutRequiredMixin, self).dispatch(*args, **kwargs)

然后在你的观点中使用它:

class RegisterView(LogoutRequiredMixin):

    def get(...):
        ...

答案 2 :(得分:0)

我使用的是基于类的视图,因此,我必须使用mixin:

class NotLoggedAllow(UserPassesTestMixin):
    login_url = '/profile/'

    def test_func(self):
        return not self.request.user.is_authenticated()

class Register_vw(NotLoggedAllow, FormView):

这样我只需要在每个视图中添加我的mixin的名称,它确实拒绝访问已登录的用户。 Nailed @Moses Koledoye,谢谢大家!