Get user group in a template Get user group in a template django django

Get user group in a template


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.


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


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

# -*- coding:utf-8 -*-from __future__ import unicode_literals# Stdlib imports# Core Django importsfrom django import template# Third-party app imports# Realative imports of the 'app-name' packageregister = 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 %}