pythondjangodjango-viewsdjango-users

How can I check if an user is superuser in django


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?


Solution

  • 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