load m2m fields objects

 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
27
28
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] )

More like this

  1. Generic CSV Export by zbyte64 4 years, 11 months ago
  2. Pagination Alphabetically compatible with paginator_class by vascop 1 year, 1 month ago
  3. Paginator TemplateTag by trbs 5 years, 1 month ago
  4. Cookie based flash errors and notices (a la Rails) by alexk 4 years, 8 months ago
  5. Photologue wiki-syntax templatetag by yeago 4 years, 8 months ago

Comments

(Forgotten your password?)