AlexW
AlexW

Reputation: 2589

Django - Show/hide urls in base html dependant on user group?

I want to try and show or hide urls in my navigation page based on user group. currently i am adding to the top of every view and sending through a value to the template and checking against that, but this doesnt seem too efficient, also if a view does not require auth and that value is not set, will that break the template?

is there a better way to do this? like a global.py where i could check and set then use it in any template? or something completely different altogether?

view.py

Authorised_user = ''
if request.user.is_authenticated():
    Authorised_user = 'IT'

@login_required
def index(request):

    return render(request, 'service/index.html', {
        'Authorised': Authorised_user,
    })    

template.html

{% if Authorised == 'IT' or Authorised =='Netwworks' %}
 <a href="link">Link</a>
{% endif %}

Upvotes: 3

Views: 5055

Answers (3)

Aaron Scheib
Aaron Scheib

Reputation: 358

Easiest way around this for me was https://stackoverflow.com/a/17087532/8326187. Here you don't have to create a custom template tag.

  {% if request.user.groups.all.0.name == "groupname" %}
    ...
  {% endif %}

Upvotes: 1

ohrstrom
ohrstrom

Reputation: 2970

i do have the user groups in django admin

Based on Get user group in a template

Create user_tags.py / group_tags.py at an appropriate place. e.g. auth_extra/templatetags/user_tags.py

from django import template

register = template.Library()

@register.filter('in_group')
def in_group(user, group_name):
    return user.groups.filter(name=group_name).exists()

Then in your template:

{% load user_tags %}

{% if request.user|in_group:"IT"%}
  <a href="link">IT only link</a>
{% endif %}

{% if request.user|in_group:"Netwworks"%}
  <a href="link"> Netwworks only link</a>
{% endif %}

Upvotes: 3

Ashutosh Sharma
Ashutosh Sharma

Reputation: 1

You need to create context_processors.py and create a function say

def foo():
   Authorised_user = ''
   if request.user.is_authenticated():
     Authorised_user = 'IT'

Then in setttings TEMPLATE_CONTEXT_PROCESSORS = ("path_to_context_processor.foo") this way you can use foo variable in all the templates without explicitly defining in all the views. You can also have a look here:https://rubayeet.wordpress.com/2009/10/31/django-how-to-make-a-variable-available-in-all-templates/

Upvotes: 0

Related Questions