How to check (in template) if user belongs to a group

后端 未结 9 1880
广开言路
广开言路 2020-12-07 20:38

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

9条回答
  •  被撕碎了的回忆
    2020-12-07 21:11

    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 %}

提交回复
热议问题