views:

23

answers:

1

Does anyone know a good way to solve this other problem I have. My site shows menus based on a users privs. I have a function that returns the privs as a dictionary as below:

return {"manage_entries":True, "manage_members":False, 
   "manage_something_else":True}

I passed in each priv to my base template that includes the navigation bar and use simple {% if priv %} to decide if I am going to show the menu item or not. It works fine except...

I need to pass the privs in the context of every view as they all include the base.html template and thus menu. There are lots of views so this is stupid. There must be a better way!

Cheers

Rich

+2  A: 

One way to do this is to write a simple custom template context processor. This is as simple as a function that accepts an instance of HttpRequest and returns a dictionary. In your case the dictionary can contain a list of the privileges for the current user.

For e.g.

# This is our processor. 
def append_privileges(request):
    privileges = get_privs(request.user)
    return dict(privileges = privileges)

Where get_privs is the method that will return the dictionary of privileges as you have indicated in your question.

Now add this processor to the TEMPLATE_CONTEXT_PROCESSORS setting in your settings.py. Generally this variable is not present in settings. When you add it, make sure that you copy the existing default and then append to it. For e.g.

TEMPLATE_CONTEXT_PROCESSORS = (
    # copied from docs.
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.contrib.messages.context_processors.messages",

    # appended custom value
    "app.utils.append_privileges",
)

Finally in your base template expect the privileges variable.

# I've added a pprint to test. You'll obviously need to do more. 
{{ privileges|pprint }}

This will make sure that all your views will automatically return a context with a correct privileges variable.

Manoj Govindan
Thanks so much Manoj, that seems perfect! I really appreciate you putting your time into saving mine! Stackoverflow is an amazing tool for developers.
Rich
@Rich: glad to help. Pay it forward :)
Manoj Govindan