Charlesliam
Charlesliam

Reputation: 1313

Django admin, how to check properly user's permission in django template?

Newbie here. My application name is ccad. And the model name is logbook. User A has no permission to edit, add or delete the logbook model from an available user permission.

So I tried hiding the save, save and continue editing, save and add another buttons from User A.

I followed the advised I found in SO. Here's from picomon inquiry that was answered by Sid. And daniel the same inquiry.

I ended up writing the code below to my template.

change_form.html located at {{template folder}}/admin/app_name/model_name/

 {% if perms.ccad.add_logbook %}
    <li><input type="submit" value="{% trans 'Save ' %}" class="grp-button grp-default" name="_save" {{ onclick_attrib }}/></li>     
    <li><input type="submit" value="{% trans 'Save and add another' %}" class="grp-button" name="_addanother" {{ onclick_attrib }} /></li>
    <li><input type="submit" value="{% trans 'Save and continue editing' %}" class="grp-button" name="_continue" {{ onclick_attrib }}/></li>        
 {% endif %}

But the user with no permission can still see the buttons I mention.

I also try changing {% if perms.ccad.add_logbook %} to {% if perms.ccad.can_add_logbook %} with no avail.

What's best way to do this?

Upvotes: 3

Views: 2899

Answers (1)

kanu
kanu

Reputation: 726

Start with checking the perms variable in the template context. Add a ...{{ perms }}... somewhere visible to the template. It should render like this ...<django.contrib.auth.context_processors.PermWrapper object at X>....

If this is not the case you are missing the permissions in the template.

Verify that your settings TEMPLATE_CONTEXT_PROCESSORS tuple contains a django.contrib.auth.context_processors.auth.

Also make sure to use a RequestContext not a Context when rendering the template.

If you finally see a PermWrapper but your permission check still doesn't work change the previous debug to ...{{ perms.ccad }}.... This should output something similar to "set([u'ccad.add_...',...]).

If not then your app might not be called ccad.

Finally before creating the if condition be sure that the permission returns something `...{{ perms.ccad.add_logbook }}...´. This should return either True or False.

Now that i am at the end i noticed that your problem is the other way around and all I wrote so far is useless. :)

add {{ user.is_superuser }} to your template. If its True the current user has superuser rights that return always True even for {{ perms.omg.can_facepalm }}

Upvotes: 5

Related Questions