Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django request.user.is_superuser doesn't work

I want to show a button if the user is a superuser. I've found differents examples but my code doesn't work. The button doesn't appear. Anybody knows why?

views.py

def inici(request):    
zones = Zona.objects.all()    
return render_to_response('principal/inici.html', dict(zones=zones),
    context_instance = RequestContext(request))

inici.html

{% if not user.is_authenticated %}
     ....
{% else %}  
<ul>                    
    <li class="nivell1">
    <a href="/accounts/logout/?next=/">Logout</a> 
    </li>               
    <li class="nivell1">
    <a class="nivell1" herf="#"> Configuració </a>          
    </li>

    {% if request.user.is_superuser %}                      
    <li class="nivell1">
        <a href="zona/crear/">Crear zona</a>
    </li>   
    {% endif %}             
</ul>                   
{% endif %}

I only have a user in the database and he is a super user. I can see the "logout" button and the other one, but not the "crear zona" button.

like image 330
user2170928 Avatar asked Jul 05 '13 12:07

user2170928


People also ask

How do I know if a user is super user?

Superuser privileges are given by being UID (userid) 0. grep for the user from the /etc/password file. The first numeric field after the user is the UID and the second is the GID (groupid). If the user is not UID 0, they do not have root privileges.

What is is_ active in Django?

is_active. Boolean. Designates whether this user account should be considered active. We recommend that you set this flag to False instead of deleting accounts; that way, if your applications have any foreign keys to users, the foreign keys won't break.

How does request user work in Django?

user is User model object. You cannot access request object in template if you do not pass request explicitly. If you want access user object from template, you should pass it to template or use RequestContext.


1 Answers

You want this Generic view:

class IniciView(ListView):
    template_name = 'principal/inici.html'
    model = Zona

are the context processors in settings?

This is more redeable:

{% if user.is_authenticated %}
    <ul>                    
      <li class="nivell1">
        <a href="/accounts/logout/?next=/">Logout</a> 
      </li>               
      <li class="nivell1">
        <a class="nivell1" herf="#"> Configuració </a>          
      </li>

    {% if user.is_superuser %}                      
      <li class="nivell1">
        <a href="zona/crear/">Crear zona</a>
      </li>   
    {% endif %}             
</ul>  
{% else %}  
    ...
{% endif %}

I've changed {% if request.user.is_superuser %} to {% if user.is_superuser %}

like image 159
Leandro Avatar answered Oct 24 '22 02:10

Leandro