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
- Check Group Membership Filter by Mogga 3 years, 10 months ago
- Using Pygments with reST by joshua 5 years, 2 months ago
- Twitterfy by dougal 2 years, 8 months ago
- Rendering a form by looping through its fields in a template by simon 3 years, 8 months ago
- Currency Object by Rupe 2 years, 12 months ago
Comments
maybe you could use user.groups.values('name') just to make it more efficient
#
Thanks, good improvement:
#
made a few mods so it can accept multiple group names... here it is -> 895
#
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'))#
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.
#
awesomeness. and for the n00bs like me, don't forget to import force_unicode:
#
This filter gives an error in Django 1.3.
Wrapping it with if user.is_authenticated(): fixes the problem.
#