Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 to check this in base.html which is an extending template (it does not have it's own view function)?

All of my templates extends base.html so it is not good to check it in each view.

The base.html contains upper bar, which should contain buttons depending on in which group logged user is (Customers, Sellers).

In my base.html is:

{% if user.is_authenticated %}

which is not enough because I have to act differently to users from Customers and users from Sellers.

So the thing I want is:

{% if user.in_group('Customers') %}
 <p>Customer</p>
{% endif %}
{% if user.in_group('Sellers') %}
<p>Seller</p>
{% endif %}
like image 771
Milano Avatar asked Sep 25 '22 17:09

Milano


1 Answers

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/dev/howto/custom-template-tags/

like image 103
mishbah Avatar answered Oct 18 '22 22:10

mishbah