How to restrict access by user groups in Django class based view?

Viewed 1780

VIEW

Problem: I want to use permission restriction in django class based views. if login user is belong from students group then i want to redirect to student-dash url. if user from teacher it's redirect to teacher-dash url. if student user try to access the teacher dashboard then i want to restrict that student user from teacher dashboard and render 404 error? I would be grateful for any help.

   class STListView(ListView):
    queryset = Article.objects.exclude(story_status='sn')
    template_name = 'index_page.html'
    context_object_name = 'list'

    def get_context_data(self, **kwargs):
        context = super(STListView, self).get_context_data(**kwargs)
        group = self.request.user.groups.filter(user=self.request.user)[0]
        if group.name == "student":
            return HttpResponseRedirect(reverse('student-dash'))
        elif group.name == "teacher":
            return HttpResponseRedirect(reverse('teacher-dash'))
        elif group.name == "Manger":
            return HttpResponseRedirect(reverse('manger-dash'))
        return context
1 Answers

There are some ways to archive it,

Try to take a look to the permission_required decorator.

from django.contrib.auth.decorators import permission_required

@permission_required('user', login_url='/redirect_to_student/')
def student_view(request):
    ...

If the user that is making the request, does not meet the permissions, they will be redirected to the login_url (that it could be any URLs of your application)

Another approach could be using the user_passes_test decorator.

if the function is passed, the user can see the view, otherwise will be redirected to specific URLs of your application:

from django.contrib.auth.decorators import user_passes_test

def email_check(user):
    return user.groups == 'student'

@user_passes_test(email_check)
def my_view(request):
    ...

Here is the Django documentation about the permissions

Related