from django.template import Library, Node, Variable register = Library() class LoadFormObjectsNode( Node ): def __init__( self, form_objects, var_name ): self.var_name = var_name form, self.field = form_objects.split('.') self.form = Variable(form) def render( self, context ): form = self.form.resolve( context ) object_ids = form.data.getlist(self.field) objects = form.fields[self.field].queryset objects = objects.filter(pk__in=object_ids) context[self.var_name] = objects return '' @register.tag def load_form_objects( parser, token ): """Parse template tag: {% load_form_objects form.objects as objects %}""" bits = token.contents.split() if len( bits ) != 4: raise TemplateSyntaxError, "load_form_objects form.objects as objects" if bits[2] != 'as': raise TemplateSyntaxError, "third argument to the load_form_objects tag must be 'as'" return LoadFormObjectsNode( bits[1], bits[3] )