Form splitting/Fieldset templatetag

 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
29
30
31
32
33
34
import copy

from django import template
from django import forms
from django.utils.datastructures import SortedDict

register = template.Library()

def get_fieldset(parser, token):
    try:
        name, fields, as_, variable_name, from_, form = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError('bad arguments for %r'  % token.split_contents()[0])

    return FieldSetNode(fields.split(','), variable_name, form)

get_fieldset = register.tag(get_fieldset)


class FieldSetNode(template.Node):
    def __init__(self, fields, variable_name, form_variable):
        self.fields = fields
        self.variable_name = variable_name
        self.form_variable = form_variable

    def render(self, context):
        
        form = template.Variable(self.form_variable).resolve(context)
        new_form = copy.copy(form)        
        new_form.fields = SortedDict([(key, value) for key, value in form.fields.items() if key in self.fields])

        context[self.variable_name] = new_form

        return u''

More like this

  1. BetterForm with fieldsets and row_attrs by carljm 5 years, 2 months ago
  2. Fieldsets for Views by Nad/ 4 years, 3 months ago
  3. SectionedForm by marinho 5 years, 10 months ago
  4. Remove named field from fieldsets by dokterbob 4 years, 5 months ago
  5. Form row filter by kylefox 6 years, 2 months ago

Comments

gregb (on August 9, 2009):

Thanks for this snippet - very handy. I created a similar "excluding" tag which works in the same way but excludes the listed fields - using the two together saves a bit of typing especially if you just want to split out a few fields from a long form into their own fieldset.

#

czartur (on August 8, 2011):

I would personally recommend to change this:

    #new_form.fields = SortedDict(
        #[(key, value) for key, value in form.fields.items() 
         #if key in self.fields])

to that:

    new_form.fields = SortedDict(
        [(key, form.fields[key]) for key in self.fields]
    )

So you can preserve ordering in your forms.

Apart from that – Brilliant snippet, saved me ton of work.

#

benjaoming (on January 17, 2012):

This is obviously a classic! Thanks a million :)

#

(Forgotten your password?)