Login

Check Group Membership Filter

Author:
Mogga
Posted:
July 18, 2008
Language:
Python
Version:
.96
Score:
-3 (after 3 ratings)

Derived from 847 but allows for checks against multiple groups...

 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
26
from django import template
from django.utils.safestring import SafeUnicode

register=template.Library()

@register.filter
def in_group(user, group):
	"""Returns True/False if the user is in the given group(s).
	Usage::
		{% if user|in_group:"Friends" %}
		or
		{% if user|in_group:"Friends,Enemies" %}
		...
		{% endif %}
	You can specify a single group or comma-delimited list.
	No white space allowed.
	"""
	import re
	if re.search(',', group): group_list = re.sub('\s+','',group).split(',')
	elif re.search(' ', group): group_list = group.split()
	else: group_list = [group]
	user_groups = []
	for group in user.groups.all(): user_groups.append(str(group.name))
	if filter(lambda x:x in user_groups, group_list): return True
	else: return False
in_group.is_safe = True

More like this

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

Comments

Please login first before commenting.