ped*_*vgp 3 django django-views
我想创建一个 Mixin,它将:首先 - 检查用户是否通过身份验证,如果没有,重定向到登录 url。如果是... 第二 - 检查用户是否有定义的配置文件(用户),如果没有,重定向到配置文件创建,否则,允许用户访问视图。
我打算做一些类似的事情:
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
Run Code Online (Sandbox Code Playgroud)
但我对如何覆盖handle_no_permission()和dispatch()方法感到困惑。
我通过以下方式解决了这个问题:
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
Run Code Online (Sandbox Code Playgroud)
现在每个需要 Profile 的视图都继承自 ProfileRequiredMixin,它将首先测试登录(如果没有,则重定向到登录创建),然后检查 Profile,如果不存在则重定向到 Profile 创建。
| 归档时间: |
|
| 查看次数: |
1238 次 |
| 最近记录: |