from django import template
from django.conf import settings
+from django.contrib.contenttypes.models import ContentType
register = template.Library()
class MembersofNode(template.Node):
def __init__(self, collection, model, as_var):
self.collection = template.Variable(collection)
- self.model = template.Variable(model)
+ self.model = model
self.as_var = as_var
def render(self, context):
try:
collection = self.collection.resolve(context)
- model = self.model.resolve(context)
- context[self.as_var] = collection.members.with_model(model)
+ context[self.as_var] = collection.members.with_model(self.model)
except:
pass
- return settings.TEMPLATE_STRING_IF_INVALID
-
-
+ return ''
+
+
def do_membersof(parser, token):
"""
- {% membersof <collection> with <model> as <var> %}
+ {% membersof <collection> with <app_label>.<model_name> as <var> %}
"""
params=token.split_contents()
tag = params[0]
if params[2] != 'with':
raise template.TemplateSyntaxError('"%s" template tag requires the third parameter to be "with"' % tag)
+
+ try:
+ app_label, model = params[3].strip('"').split('.')
+ ct = ContentType.objects.get(app_label=app_label, model=model)
+ except ValueError:
+ raise template.TemplateSyntaxError('"%s" template tag option "with" requires an argument of the form app_label.model (see django.contrib.contenttypes)' % tag)
+ except ContentType.DoesNotExist:
+ 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)
if params[4] != 'as':
raise template.TemplateSyntaxError('"%s" template tag requires the fifth parameter to be "as"' % tag)
- return MembersofNode(collection=params[1], model=params[3], as_var=params[5])
+ return MembersofNode(collection=params[1], model=ct.model_class(), as_var=params[5])
register.tag('membersof', do_membersof)
\ No newline at end of file