How can I adjust the page permission according to the member role?

I’m using django-groups-manager.

Screenshot

I can set the page permission according to the user in the group in the decorator below. So how can I set this up for the member’s role? Thus, only the member with this role can see the page. I’m waiting for your help.

decorators.py

def sahip_only(view_func):
    def wrapper_function(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            group = request.member.groups.all()[0].name
        if group == 'PC':
            return redirect('home')
        if group == 'Console':
            return view_func(request, *args, **kwargs)
        else:
            return HttpResponse('You are not authorized to access this page.')
    return wrapper_function

views.py

@login_required(login_url='/accounts/login/')
@sahip_only
def calisan(request):
    queryset = request.user.groups
    form = CalisanForm(request.POST or None, group_qs=queryset)
    if form.is_valid():
        user = form.save()
        group = form.cleaned_data['group']
        user.groups.add(AGroup.objects.get(name=group))
        username = form.cleaned_data['username']
        member = Member.objects.create(first_name=username)
        group = Group.objects.get(name=form.cleaned_data['group'])
        group.add_member(member, [form.cleaned_data.get('roles')])
        user.save()
        password = form.cleaned_data.get('password1')
        new_user = authenticate(username=user.username, password=password)
        return redirect('home')
    return render(request, 'accounts/calisan/calisan.html', {'form': form, 'title': 'Üye Ol'})

forms.py

class CalisanForm(UserCreationForm):
    username = forms.CharField(max_length=100, label='Kullanıcı Adı')
    email = forms.EmailField(max_length=200, help_text='Required')
    password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput)
    password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput)
    group = forms.ModelChoiceField(queryset=Group.objects.all(), widget=forms.widgets.RadioSelect(), empty_label=None)
    roles = forms.ModelChoiceField(queryset=GroupMemberRole.objects.all(), widget=forms.widgets.RadioSelect(), empty_label=None)

    def __init__(self, *args, **kwargs):
        qs = kwargs.pop("group_qs")
        super().__init__(*args, **kwargs)
        self.fields["group"].queryset = qs

    class Meta:
        model = User
        fields = [
            'username',
            'email',
            'password1',
            'password2',
            'group',
            'roles',
        ]

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Parolalar eşleşmiyor!")
        return password2

    def clean_email(self):
        email = self.cleaned_data.get('email')
        lenghtw = len(User.objects.filter(email=email))
        if lenghtw > 0 :
            raise forms.ValidationError('Bu email adresine sahip bir kullanıcı zaten var.')
        return email

I couldn’t find how to do it. Is there someone to help?

What’s the error you are seeing? Have you tried to add print output to make sure your decorator is called correctly, and to figure out what values are being passed?

I’m not getting an error. The decorator shows the page according to the group I have determined.

I want to show the page not by group, but by the role of the member. How can I adapt it according to the role of the member?

Merhaba!
I’m not a pro but I think maybe I can help answer this.

in your views.py make the following changes:

@login_required(login_url='/accounts/login/')
@allowed_users(allowed_roles=['sahip']
def calisan(request):
    queryset = request.user.groups
    form = CalisanForm(request.POST or None, group_qs=queryset)
    if form.is_valid():
        user = form.save()
        group = form.cleaned_data['group']
        user.groups.add(AGroup.objects.get(name=group))
        username = form.cleaned_data['username']
        member = Member.objects.create(first_name=username)
        group = Group.objects.get(name=form.cleaned_data['group'])
        group.add_member(member, [form.cleaned_data.get('roles')])
        user.save()
        password = form.cleaned_data.get('password1')
        new_user = authenticate(username=user.username, password=password)
        return redirect('home')
    return render(request, 'accounts/calisan/calisan.html', {'form': form, 'title': 'Üye Ol'})

Then for your decorators.py:

def unauthenticated_user(view_func): #view_func is the function from the views.py such as login
    def wrapper_func(request, *args, **kwargs): #this wraps the view_func in the wrapper
        if request.user.is_authenticated: #if the user is logged in then it redirects correctly to below line
            return redirect('ENTER PAGE TO DIRECT HERE')
        else:
            return view_func(request, *args, **kwargs) #otherwise it allows the user to try to login
    return wrapper_func

def allowed_users(allowed_roles=[]):
    def decorator(view_func):
        def wrapper_func(request, *args, **kwargs):
            group = None
            if request.user.groups.exists():
                group = request.user.groups.all()[0].name
            if group in allowed_roles:
                return view_func(request, *args, **kwargs)
            else:
                return HttpResponse('You are not authorized to access this page.")
        return wrapper_func
    return decorator