Monday 30 November 2020

Django restricting a Class Based View page depending on a User attribute / Group etc.

The following code is an example of how you can make it so users get redirected depending on conditions taken from their User model . 


This code is to go in a Class Based View. 

1 2 3 4 def dispatch(self, request, *args, **kwargs): if request.user.username == 'david.smith': return redirect('home_page') return super().dispatch(request, *args, **kwargs)



This example would redirect the user 'david.smith'.  This next example would redirect if the User does not belong to the group that we want. 


def dispatch(self, request, *args, **kwargs): if request.user.groups.filter(name = 'Coordinator').exists(): return super().dispatch(request, *args, **kwargs) return redirect('home_page')


No comments: