Login

in_group template filter

Author:
whiteinge
Posted:
July 2, 2008
Language:
Python
Version:
.96
Score:
7 (after 7 ratings)

Allows you to search if a user belongs to a given group.

Along the same lines as snippet 390, but uses a regular if tag so it is more flexible.

(Updated for efficiency. Running a boolean test on a QuerySet avoids a bit of unnecessary overhead.)

(Updated to accept a list of groups.)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
@register.filter
def in_group(user, groups):
    """Returns a boolean if the user is in the given group, or comma-separated
    list of groups.

    Usage::

        {% if user|in_group:"Friends" %}
        ...
        {% endif %}

    or::

        {% if user|in_group:"Friends,Enemies" %}
        ...
        {% endif %}

    """
    group_list = force_unicode(groups).split(',')
    return bool(user.groups.filter(name__in=group_list).values('name'))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

dnordberg (on July 3, 2008):

maybe you could use user.groups.values('name') just to make it more efficient

#

whiteinge (on July 3, 2008):

Thanks, good improvement:

return group in [g['name'] for g in user.groups.values('name')]

#

whiteinge (on July 19, 2008):

To check if a user is in a comma-separated list of groups just change the last line to the following (it is slightly less efficient than just checking one group):

return bool(user.groups.filter(name__in=groups.split(',')).values('name'))

#

whiteinge (on July 19, 2008):

Just re-ran the speed tests and I was mistaken -- there is virtual no performance difference, so I updated the main snippet. Thanks for the idea.

#

andrea (on December 11, 2010):

awesomeness. and for the n00bs like me, don't forget to import force_unicode:

from django.utils.encoding import force_unicode

#

saundersmatt (on October 19, 2011):

This filter gives an error in Django 1.3.

Wrapping it with if user.is_authenticated(): fixes the problem.

#

seafangs (on September 3, 2012):

This snippet is extremely useful, but saundersmatt is right. I recommend replacing the last two lines of the snippet with this:

if user.is_authenticated():
    group_list = force_unicode(groups).split(',')
    return bool(user.groups.filter(name__in=group_list).values('name'))
else:
    return False

#

Please login first before commenting.