Home > Enterprise >  Django user permission on generate specific view depending on user group
Django user permission on generate specific view depending on user group

Time:02-21

I am new to Django user permission and is setting it up for the first time. I need to generate different views after user has logged in. The views being generated depends on the group that the user belongs to.

Say we have two users called user1 and user2

user1 belongs to group1

user2 belongs to group1 and group2

For user1 I will like to render a view that is specific for group1.

For user2 the view rendered must be have both the content specific for group1 and group2

In my current views.py I am only able to decide if a user has logged in and if true the page staffLoginIndex.html will be rendered. To check which group the user belongs to, should this check be done in the actual get(self, request, *args, **kwargs)?

from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin

# Create your views here.
class StaffLoginIndexView(LoginRequiredMixin, View):
    login_url = '/accounts/login/'

    def get(self, request, *args, **kwargs):
        #Check which group the user belongs to
        
        context = dict()
        context['user'] = request.user
        return render(request, template_name='staff/staffLoginIndex.html', context=context)

CodePudding user response:

You can have access to users group by using request.user.groups.all() and it will return a QuerySet. Then you can customize your template according to each users group.

  • Related