Django-如何使用LoginRequired和PermissionRequired进行不同的重定向? [英] Django - How to redirect differently using LoginRequired and PermissionRequired?

查看:520
本文介绍了Django-如何使用LoginRequired和PermissionRequired进行不同的重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Mixin,它将:
首先-检查用户是否通过了身份验证,如果没有通过身份验证,则重定向到登录URL。如果是...
其次-检查用户是否具有定义的配置文件(用户),否则,重定向到配置文件创建,否则,允许用户访问视图。

I would like to create a Mixin which will: First - Check if a user is authenticated, if not, redirect to login url. If yes... Second - Check if user has a defined Profile (a user), if not, redirect to Profile creation, else, allow user to access the View.

我打算做一些类似的事情:

I was planning to do sometinhg like:

class ProfileRequiredMixin(LoginRequiredMixin,PermissionRequiredMixin):
#TODO check how multiple inheritance works treating conflicting methods
'''This Mixin should first check if user is autheticated, if not,
redirect to login. If it is, check if it has a  profile. 
If it does not, redirect to profile creation url. If it has, allow
access to view.'''
pass

但是我对如何覆盖 handle_no_permission() dispatch()方法感到困惑。

But I am confused as how to overwrite the handle_no_permission() and dispatch() methods.

推荐答案

我通过以下方式解决了这个问题:

I solved the problem in the following way:

class TestIfHasProfileMixin(UserPassesTestMixin):
    '''This Mixin should first check if user has a profile. 
    If it does not, redirect to profile creation url. If it has, allow
    access to view.'''

    def test_func(self):
        try:
            Profile.objects.get(user=self.request.user)
            return True
        except Profile.DoesNotExist:
            return False

    def handle_no_permission(self):
        '''to:[login,Profile] will signup or create profiles'''
        if self.raise_exception:
            raise PermissionDenied(self.get_permission_denied_message())
        return redirect('users:create-profile')


class ProfileRequiredMixin(LoginRequiredMixin,TestIfHasProfileMixin):
    '''This Mixin should first check if user is autheticated, if not,
    redirect to login. If it is, check if it has a profile. 
    If it does not, redirect to profile creation url. If it has, allow
    access to view.'''
    pass

现在,每个需要Profile的视图都继承自ProfileRequiredMixin,它将首先测试登录(如果没有登录,则重定向到登录创建),然后检查Profile,如果不存在,则重定向到Profile创建。

Now every view that requires a Profile inherits from ProfileRequiredMixin, which will first test for login (redirect to login creation if there is not) and after that check for Profile and redirect to Profile creation if none exists.

这篇关于Django-如何使用LoginRequired和PermissionRequired进行不同的重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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