How can I check if an user is superuser in django
Asked Answered
H

2

10

I'm listing registered users on a ListView page and I'm trying to show if user is superuser or not.

My main user is created with python manage.py createsuperuser command and I'm sure it is a superuser beacuse I've checked from admin panel too.

When I try to print if it is superuser or not my code always shows a False output. Here are my codes:

views.py

@method_decorator(staff_member_required, name='dispatch')
class Uyeler(ListView):
    model = User
    paginate_by = 40
    ordering = ['-pk']
    template_name = "panel/uyeler.html"

and in template file:

{% for obj in object_list %} 
  {% if obj.is_superuser %}
    SuperUser 
  {% else %}
    Not SuperUser {{ obj.is_superuser }}
  {% endif %}
    
{% endfor %}

And my html output is "Not SuperUser False" for all users including my superuser account. Any ideas?

Hairstreak answered 23/12, 2020 at 9:0 Comment(3)
No change. I'm printing it just for information anyway.Hairstreak
What does "admin pannel" say about superuser value ?Prognosticate
in admin panel superuser box is checked.Hairstreak
G
2

I tried in my code and it's working maybe there's issue in your data this is how my code looks like

views.py

def user_detail(request):
  user_detail = CustomUser.objects.filter(id=id)
  return(request, 'user_datail.html', {'user_detail': user_detail})

user_datail.html

{% for i in user_detail %}
  {% if i.is_superuser %}
     <td class="text-center"><span class="btn btn-success">You</span> 
     </td>
  {% else %}
    <td class="text-center"><span class="btn btn-info">Agent</span> 
    </td>
  {% endif %}
{% endfor %}

output

view image

Greysun answered 23/12, 2020 at 9:20 Comment(0)
G
21

This is my views.py, for showing current user accounts

@login_required
def account(request):
    if request.user.is_superuser: # just using request.user attributes
        accounts = get_user_model().objects.all()```
Gout answered 16/9, 2021 at 8:17 Comment(0)
G
2

I tried in my code and it's working maybe there's issue in your data this is how my code looks like

views.py

def user_detail(request):
  user_detail = CustomUser.objects.filter(id=id)
  return(request, 'user_datail.html', {'user_detail': user_detail})

user_datail.html

{% for i in user_detail %}
  {% if i.is_superuser %}
     <td class="text-center"><span class="btn btn-success">You</span> 
     </td>
  {% else %}
    <td class="text-center"><span class="btn btn-info">Agent</span> 
    </td>
  {% endif %}
{% endfor %}

output

view image

Greysun answered 23/12, 2020 at 9:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.