How to check in template whether user belongs to some group?
It is possible in a view
which is generating the template
but what if I want
In your app create a folder 'templatetags'. In this folder create two files:
__init__.py
auth_extras.py
from django import template
from django.contrib.auth.models import Group
register = template.Library()
@register.filter(name='has_group')
def has_group(user, group_name):
group = Group.objects.get(name=group_name)
return True if group in user.groups.all() else False
It should look like this now:
app/
__init__.py
models.py
templatetags/
__init__.py
auth_extras.py
views.py
After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.
In your base.html (template) use the following:
{% load auth_extras %}
and to check if the user is in group "moderator":
{% if request.user|has_group:"moderator" %}
moderator
{% endif %}
Documentation: https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/