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

我的梦境 提交于 2019-11-28 18:38:32

You need custom template tag:

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() 

In your template:

{% if request.user|has_group:"mygroup" %} 
    <p>User belongs to my group 
{% else %}
    <p>User doesn't belong to mygroup</p>
{% endif %}

Source: http://www.abidibo.net/blog/2014/05/22/check-if-user-belongs-group-django-templates/

Docs: https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/

fuser60596

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" %} 
    <p>moderator</p> 
{% endif %}

Documentation: https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/

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" %} 
    <p>User belongs to my group 
{% else %}
    <p>User doesn't belong to mygroup</p>
{% endif %}

EDIT: added line with template tag loading as was advised in comments.

muccix

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" %} 
    <p>User belongs to my group 
{% else %}
    <p>User doesn't belong to mygroup</p>
{% endif %}

In your template

{% ifequal user.groups.all.0.name "user" %}
  This is User
{% endifequal %}
  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!