Ad

Django User Permission On Generate Specific View Depending On User Group

- 1 answer

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)
Ad

Answer

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.

Ad
source: stackoverflow.com
Ad