Stephen
Stephen

Reputation:

Get user group in a template

I want to display a menu that changes according to the user group of the currently logged in user, with this logic being inside of my view, and then set a variable to check in the template to determine which menu items to show....I'd asked this question before, but my logic was being done in the template. So now I want it in my view...The menu looks as below

   <ul class="sidemenu">
    <li><a href="/">General List </a></li>
    <li><a href="/sales_list">Sales List </a></li>
    <li><a href="/add_vehicle">Add a New Record </a></li>
    <li><a href="/edit_vehicle">Edit Existing Record </a></li>
    <li><a href="/filter">Filter Records </a></li>
    <li><a href="/logout">Logout </a></li>
  </ul>

Suppossing the user is management, they'll see everything...But assuming the user is in the group sales, they'll only see the first two and the last two items...and so on. I also want a dynamic redirect after login based on the user's group. Any ideas?

Upvotes: 23

Views: 31615

Answers (5)

Serhat
Serhat

Reputation: 1

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 %}

Upvotes: 0

CentOS
CentOS

Reputation: 141

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

Upvotes: 2

Kishor Pawar
Kishor Pawar

Reputation: 3526

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

Upvotes: 18

Lucas Simon
Lucas Simon

Reputation: 461

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 %}

Upvotes: 17

Van Gale
Van Gale

Reputation: 43902

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.

Upvotes: 44

Related Questions