in_group template filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django import template
from django.utils.safestring import SafeUnicode

@register.filter
def in_group(user, group):
    """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 %}

    """
    if not isinstance(group, SafeUnicode):
        raise template.TemplateSyntaxError("Group name needs to be a string.")

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

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')]

#

Mogga (on July 18, 2008):

made a few mods so it can accept multiple group names... here it is -> 895

#

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.

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.