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
Watch out that you'll get an exception if the group does not exist in the DB.
The custom template tag should be:
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):
try:
group = Group.objects.get(name=group_name)
except Group.DoesNotExist:
return False
return group in user.groups.all()
Your template:
{% if request.user|has_group:"mygroup" %}
User belongs to my group
{% else %}
User doesn't belong to mygroup
{% endif %}