Django Group permission how to print it in template

Viewed 769

if the customer sign in and he has permission to see the data that the admin has given to him, he will see the data after he sign in, but if the admin doesn't give him permission, this message will appear You are not authorized to view this page

in my case no matter what the permission given the admin this message always appears You are not authorized to view this page

from .decorators import unathenticated_user, allowed_users,staff_only
from django.contrib.auth.models import Group

@login_required(login_url='loginpage')
@staff_only

def adminpage(request):
    return render(request, 'Homepage/adminsite.html')
def loginpage(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user:
            username = request.POST['username']
            request.session['username'] = username
            return redirect('adminpage')
        else:

            return render(request, 'Homepage/adminlogin.html')

    return render(request, 'Homepage/adminlogin.html')

this is my decorators.py

from django.http import HttpResponse
from django.shortcuts import redirect




def unauthenticated_user(view_func):
    def wrapper_func(request, *args, **kwargs):
        if request.user.is_staff:
            return redirect('adminpage')
        else:
            return view_func(request, *args, **kwargs)
    return wrapper_func



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

def staff_only(view_func):
    def wrapper_function(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            group = request.user.groups.all()[0].name

        if group == 'registrar':
            return redirect('adminpage')

        if group == 'admin':
            return view_func(request, *args, **kwargs)

    return wrapper_function

this is my admin site (permission)

enter image description here

this is my login looks like

enter image description here

after I sign in (UPDATED ERROR)

enter image description here

thanks in advance

this is my html

NOTE I dont know if this html is working. because of my logic error, I am sorry for that, I just want to print the permissions that admin given to the customer.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% if request.user|group:"registrar" %}
    <p>User belongs to my group</p>
{% else %}
    <p>User does not belong to my group</p>
{% endif %}

</body>
</html>

this is my urls.py

urlpatterns = [
       path('adminpage/', Homepage.views.adminpage, name='adminpage'),
       path('loginpage/', Homepage.views.loginpage, name='loginpage'),
  ]

this is the error in my html

if you have any question, I am happy to provide an answer inorder to answer this questionenter image description here

2 Answers
def staff_only(view_func):
    def wrapper_function(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            group = request.user.groups.all()[0].name
        if group == 'registrar':
            return redirect('adminpage')

        if group == 'admin':
            return view_func(request, *args, **kwargs)
        return redirect("loginpage")

    return wrapper_function

This function is missing case when a user does not have required groups, in this case, either we should either redirect a user to login page send to another page or display like "You don't have access to this page"

You are asking how to print but as obvious you have some other problems. The other answer has solved the problem on your staff_only decorator. Since you did not cover every case your decorator where returning None. It has been corrected by the other user but to make all in one place i will give detail too.

def staff_only(view_func):
    def wrapper_function(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            groups = list(request.user.groups.all().values_list('name', flat=True))

        if 'admin' in groups or 'registrar' in groups:
            """I assume that registrar is also staff"""
            return view_func(request, *args, **kwargs)

        return redirect("loginpage")

    return wrapper_function

In your decorator you were only taking users first group and compare it's name. However users may have multiple groups. Thus you need to check the whole list. My solution above gets all groups in a list and check if it fits the conditions and do continue to the view or redirect.

In your template you are using not existing template filter group.

You may change it as following:

<body>
{% for group in request.user.groups.all %}
    {% if group.name == 'registrar' %}
        <p>User belongs to my group</p>
    {% endif %}
{% endfor %}
</body>

If you want to print all groups you may do the following.

<body>
<ul>
{% for group in request.user.groups.all %}
    <li>{{group.name}}</li>
{% endfor %}
</ul>
</body>

However the best way of checking if user has a group in template is creating a template filter for that purpose. You can check documentation.

@register.filter(name='has_group')
def has_group(user, group_name):
    return user.groups.filter(name=group_name).exists()

in your template:

<body>
{% if request.user|has_group:"registrar" %}
    <p>User belongs to my group</p>
{% else %}
    <p>User does not belong to my group</p>
{% endif %}
</body>
Related