1 from django import template
2 from django.conf import settings
3 from django.contrib.contenttypes.models import ContentType
6 register = template.Library()
9 class MembersofNode(template.Node):
10 def __init__(self, collection, model, as_var):
11 self.collection = template.Variable(collection)
15 def render(self, context):
17 collection = self.collection.resolve(context)
18 context[self.as_var] = collection.members.with_model(self.model)
24 def do_membersof(parser, token):
26 {% membersof <collection> with <app_label>.<model_name> as <var> %}
28 params=token.split_contents()
32 raise template.TemplateSyntaxError('"%s" template tag requires six parameters' % tag)
34 if params[2] != 'with':
35 raise template.TemplateSyntaxError('"%s" template tag requires the third parameter to be "with"' % tag)
38 app_label, model = params[3].strip('"').split('.')
39 ct = ContentType.objects.get(app_label=app_label, model=model)
41 raise template.TemplateSyntaxError('"%s" template tag option "with" requires an argument of the form app_label.model (see django.contrib.contenttypes)' % tag)
42 except ContentType.DoesNotExist:
43 raise template.TemplateSyntaxError('"%s" template tag option "with" requires an argument of the form app_label.model which refers to an installed content type (see django.contrib.contenttypes)' % tag)
46 raise template.TemplateSyntaxError('"%s" template tag requires the fifth parameter to be "as"' % tag)
48 return MembersofNode(collection=params[1], model=ct.model_class(), as_var=params[5])
51 register.tag('membersof', do_membersof)