Check if user belongs to a group in django templates

django tips

You can also be interested in:

Generally when implementing some "authentication logic" inside a django template it's enough to check if a user has some permissions, and in such cases you can use the variable perms, which is available if (from django site):

Technically, these variables are only made available in the template context if you use RequestContext and your "django.contrib.auth.context_processors.auth", which is default. For more, see the RequestContext docs.

But could happen that you need to check if a user belongs to a certain group.

In such case you may find some good custom templatetags like this, they work well and cover all your needs.

Another approach consists in writng a custom template filter and use it with the builtin templatetag if.
I've choosen this way.

So here comes a simple template filter which checks if the user belongs to a given group. It can be easily extended to take into account more groups.

from django import template
from django.contrib.auth.models import Group

register = template.Library()

def has_group(user, group_name):
    group = Group.objects.get(name=group_name)
    return True if group in user.groups.all() else False

And in your template you can use it this way:

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

That's quite easy and does what it has to.

Subscribe to abidibo.net!

If you want to stay up to date with new contents published on this blog, then just enter your email address, and you will receive blog updates! You can set you preferences and decide to receive emails only when articles are posted regarding a precise topic.

I promise, you'll never receive spam or advertising of any kind from this subscription, just content updates.

Subscribe to this blog

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!