[Django]-Get user group in a template

43👍

The standard Django way of checking permissions is by the individual permission flags rather than testing for the group name.

If you must check group names, being aware that Users to Groups is a many-to-many relationship, you can get the first group in the list of groups in your template with something like this:

{{ user.groups.all.0 }}

or using it like this in a conditional (untested but should work):

{% ifequal user.groups.all.0 'Sales' %}
   ...
{% endif %}

If you go with the preferred permission model you would do something like the following.

...

  {% if perms.vehicle.can_add_vehicle %}
    <li><a href="/add_vehicle">Add a New Record </a></li>
  {% endif %}
  {% if perms.vehicle.can_change_vehicle %}
    <li><a href="/edit_vehicle">Edit Existing Record </a></li>
  {% endif %}

...

These are the permissions automatically created for you by syncdb assuming your app is called vehicle and the model is called Vehicle.

If the user is a superuser they automatically have all permissions.

If the user is in a Sales group they won’t have those vehicle permissions (unless you’ve added those to the group of course).

If the user is in a Management group they can have those permissions, but you need to add them to the group in the Django admin site.

For your other question, redirect on login based on user group: Users to Groups is a many-to-many relationship so it’s not really a good idea to use it like a one-to-many.

16👍

user.groups.all.0.name == "groupname"

15👍

Create a user_tags.py in your app/templatetags follow above:

# -*- coding:utf-8 -*-
from __future__ import unicode_literals

# Stdlib imports

# Core Django imports
from django import template

# Third-party app imports

# Realative imports of the 'app-name' package


register = template.Library()


@register.filter('has_group')
def has_group(user, group_name):
    """
    Verifica se este usuário pertence a um grupo
    """
    groups = user.groups.all().values_list('name', flat=True)
    return True if group_name in groups else False

And finally in template use it:

{% if request.user|has_group:"Administradores"%}
      <div> Admins can see everything </div>
{% endif %}

2👍

If you are working with Custom User Model (best practice with Django), you can create a method:

CustomUser(AbstractUser):
    # Your user stuff

    def is_manager(self):
        return self.groups.filter(name='Management').exists()

Then inside your template you just call it this way:

{% if user.is_manager %}
    {# Do your thing #}
{% endif %}

That method will be also useful validating permission in other parts of your code (views, etc.)

👤CentOS

0👍

I’ve been looking for answer to this questions and Lucas Simon’s replay is totaly works. Thanks a lot.

Before this, I used templatetags each time I was checking on the .html file like this. (It also works, but using temlpatetags is better, I think.)

{% if request.user.groups.all.0.name == "Book" %}

<!-- show this -->

{% endif %}
👤Serhat

Leave a comment