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
I'd say that the best way is:
yourapp/templatetags/templatetagname.py
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()
yourapp/templates/yourapp/yourtemplate.html:
{% load has_group %}
{% if request.user|has_group:"mygroup" %}
User belongs to my group
{% else %}
User does not belong to my group
{% endif %}
EDIT: added line with template tag loading as was advised in comments.
EDIT2: fixed minor typo.