Thursday 3 December 2020

Django how to limit the Template view depending on the Users Groups.

 What we need to do is check the Users group list from inside the ' if user.is_authenticated' statement in the template. And to do this we need to harness the power of Django's 'template tags'

Create the folder and following pages in your main app folder - in my case ‘mysite’

1 2 3 -- templatetags ---- __init__.py ---- mysite_templatetag.py

__init__.py will be a blank file .

in mysite_templatetag.py I have .

1 2 3 4 5 6 7 from django import template register = template.Library() @register.filter(name='has_group') def has_group(user, group_name): return user.groups.filter(name=group_name).exists()

 

And then in the template base.html

1 2 3 4 5 6 7 {% load mysite_templatetag %} ... {% if request.user|has_group:"Coordinator" %} <li class="nav-item"> <a class="nav-link" href="{% url 'users:user_list_view' %}">Your Surveyors</a> </li> {% endif %}


According to some instructions that should be it; however I was getting the error


template tags '%_extras' is not a registered tag library. must be one of: …


To solve this .

  1. The server will need to be rebooted.

  2. Make sure the files are in the right place

  3. I added the following to my settings.py ‘TEMPLATES’ object.



    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'mysite','templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'libraries':{ 'mysite_templatetag': 'mysite.templatetags.mysite_templatetag', } }, }, ]



Reebooted the server and now it works.