Accessing django permissions inside templates

built in permissions system is another piece of excellent functionality you get for free when you use the framework. Each “model” (database table) automatically gets create, delete and change permissions that you can assign to django users and groups. You can create custom permissions per model. Users inside groups inherit permissions assigned to groups. More on that .

Not only views but templates have access to the currently logged in user’s permissions, but it’s not entirely obvious how to get there. You need to pass a RequestContext object to the template first. Here’s how you do it.

from django.template import RequestContext
return render_to_response("mytemplate.html", context_instance=RequestContext(request))

It seems I wasn’t the only one to read the documentation and still not have the objects working in my templates. I searched the django users group and found the posted the same day I started looking at it. A comment in the documentation pointed me to the fact that you need to explicitly pass the object to the template in the render_to_response.

I suppose this highlights the value of using a comments system in documentation, with being one of the best examples I’ve seen of this.

1 Response to “Accessing django permissions inside templates”

  1. 1

    Hey, Ben. I has the same question but I found the solution. Solution is in default django.core.context_processors.auth context processor. If you will enable it in your you can access this data inside templates. For example:

    {{ perms.model_name.permission_name }}

    This will be True or False.
    Hope this will help to you and other people looking solution.

Leave a Reply

Spam Blocked

44,528 spam comments
blocked by