Login

Easy Form Structuring

Author:
jug
Posted:
July 28, 2009
Language:
Python
Version:
1.0
Score:
-4 (after 4 ratings)

With this, you can group form fields very easily. Since it does not create any html, you can use it not only to create fieldsets (with tables, lists, etc).

 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from django import forms
from django.forms.forms import BoundField

class StructuredForm:
    group_struct = []
    def groups(self):
        group_list = []
        for name, fields in self.group_struct:
            group_list.append((name, [BoundField(self, 
                                           self.fields[fname],
                                           fname) for fname in fields]))
        return group_list


#################
#
#  example form
#


class MyForm(forms.ModelForm, StructuredForm):
    group_struct = ((None,
                           ["fieldname1"]),
                       ("sectionname1",
                           ["fieldname2", "fieldname3", 
                            "fieldname4"]),
                       ("sectionname2", 
                           ["fieldname5",
                             # ...
                            ]),
                       # ...
                      )
    class Meta:
        model = MyModel
        # exclude = ...
        # ... 


#####################
#
#  example template
#

"""
<form action="#" method="post">
    {% for name, fields in form.groups %}
        {% if name %}
          <fieldset>
          <legend>{{name}}</legend>
        {% endif %}
        
        <table>
            {% for field in fields %}    
              <tr><th>{{field.label}}</th><td>{{field.errors}}{{field}}{% if field.help_text %}<br/>{{field.help_text}}{% endif %}</td></tr>
            {% endfor %}
        </table>
        
        {% if name %}    
          </fieldset>
        {% endif %}
    
    {% endfor %}
    <p>
       <input type="submit" name="submit" value="Send" />
    </p>
</form>
"""

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.