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

后端 未结 9 1877
广开言路
广开言路 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:03

    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.

提交回复
热议问题