Reputation: 1047
I have some page that displays various players of a team. In the configuration you can switch between the teams, so if you put TEAM_NAME = 'test'
it loads the test team obviously. The problem is, that if you put TEAM_NAME = 'test2'
, it starts it up for that team, but I can still change the URL to switch between teams (while I should only be able to view the team I selected)
The URL looks like this:
http://127.0.0.1:8000/team/1/player/
, where 1
would be the first created team, which is test
.
When I load the view, I would like to have some permission checks to see if the current view's team is the same as the team in the configuration.
This is the view:
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)
Upvotes: 0
Views: 45
Reputation: 25559
You could do that in get
method to block/allow access:
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)
Upvotes: 1