Search code examples
djangodjango-authenticationdjango-users

How to write user specific views?


I have a written views in django where i have more than one tab on the web page. Some of them I want to make invisible for those user whose is_staff status is False. Following is the code

   TOP_NAVIGATION_BAR = [ {'name':'home', 'href':'/my_app/home',active:False},
                          {'name':'Content', 'href':'/my_app/content',active:False},
                          {'name':'Secure', 'href':'/my_app/Secure',active:False},
                        ]

   class topnavigationbar:
         tab = TOP_NAVIGATION_BAR
         def set_active_tab(self, tab_name):
             for tab in self.tabs:
                if tab['name'] == tab_name:
                   tab['active'] = True;
                else:
                   tab['active'] = False;

         def __init__(self, active_tab):
             self.set_active_tab(active_tab)

For every view i set the top_navigation_bar active option= True.

Now I want that Secure tab should not be visible to users whose is_staff status is False. How and where can i write the query for that? Thanks


Solution

  • Another solution (involving not modifying the arguments to __init__(), which may be troublesome) is to define which URLs need is_staff in TOP_NAVIGATION_BAR, like this:

    TOP_NAVIGATION_BAR = [
        {{'name': 'Secure', 'href': '/my_app/Secure', active: False, secure: True},
        ...
    ]
    

    Now, you can carry out the check itself in the template (assuming your navigation menu appears in the template as the nav_menu context variable):

    {% for menu_item in top_menu %}
    {% if not menu_item.secure or request.user.is_staff %}
        <a href='{{ menu_item.href }}' ...
    {% endif %}
    {% endfor %}