问题描述
我有很多意见,并且有一个以上的用户类型。我希望某些视图可以由特定用户类型查看,而其他用户则看不到。
例如,只有公司才能看到此视图,为此,我在下面这样做:
@login_required
def only_company_can_view(request):
if not Company.objects.filter(owner_id=request.user.id).exists():
return HttpResponse('Permission Denied. Only Company can see this')
# > rest of the logic
return render(request,'template.html')
,并且在此之上运行得很好,可以解决我的问题,但我不喜欢这样。因为我不想每次都为公司相关视图的其余视图编写内容。
所以我正在寻找解决方案,以便可以使用装饰器或其他最佳实践
在这种情况下,有人可以帮助我吗?
解决方法
您可以将逻辑包装在装饰器中
from django.core.exceptions import PermissionDenied
from functools import wraps
def requires_company(view):
@wraps(view)
def _view(request,*args,**kwargs):
if not Company.objects.filter(owner_id=request.user.id).exists():
raise PermissionDenied
return view(request,**kwargs)
return _view
然后将装饰器用于:
@login_required
@requires_company
def only_company_can_view(request):
# … rest of the logic …
return render(request,'template.html')