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

3πŸ‘

βœ…

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 %}
πŸ‘€ohrstrom

1πŸ‘

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 %}
πŸ‘€Aaron Scheib

0πŸ‘

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/

Leave a comment