Django限制对某些对象的查看访问

时间:2016-04-04 14:40:45

标签: python django

我有一些页面显示团队中的各种玩家。在配置中,您可以在团队之间切换,因此如果您放置TEAM_NAME = 'test',它显然会加载测试团队。问题是,如果您放置TEAM_NAME = 'test2',它会为该团队启动它,但我仍然可以更改URL以在团队之间切换(而我应该只能查看我选择的团队)

网址如下所示: http://127.0.0.1:8000/team/1/player/,其中1是第一个创建的团队,test

当我加载视图时,我希望进行一些权限检查,以查看当前视图的团队是否与配置中的团队相同。

这是观点:

class PlayerList(ListView):

    model = player_model
    template_name = 'player_list.html'

    def get_team(self):
        if not hasattr(self, '_team'):
            team_id = self.kwargs.get('team_id')
            self._team = team_model.objects.get(pk=self.kwargs.get('team_id'))
        return self._team

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['team'] = self.get_team()
        return context

    def get_queryset(self, *args, **kwargs):
        queryset = super().get_queryset(*args, **kwargs)
        return queryset.filter(team_id=self.kwargs.get('team_id'))

    def get(self, request, *args, **kwargs):
        return super(PlayerList, self).get(request, *args, **kwargs)

1 个答案:

答案 0 :(得分:1)

你可以用get方法来阻止/允许访问:

from django.core.exceptions import PermissionDenied

def get(self, request, *args, **kwargs):
    team_id = self.kwargs.get('team_id')
    team = team_model.objects.get(pk=team_id)
    if team.name != TEAM_NAME: 
        raise PermissionDenied
    else:
        return super(PlayerList, self).get(request, *args, **kwargs)