Login

NewForms Readonly / Edit Pattern

Author:
FreddieP
Posted:
December 10, 2007
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

This is a little base class that I use to display forms in a readonly mode. Providing a simple javascript on the front end to allow a user to click an edit link that will show/hide the actual form.

To use it simply inherit from it. Then in your templates do the following:

{{ form.as_readonly_table }}

Other Notes

  • form.html {% for field in bound_fields %} {% include "newforms/field.html" %} {% endfor %}

  • field.html {% if field.errors %} <tr> <td>&nbsp;</td> <td>{{ field.errors }}</td> </tr> {% endif %} <tr> <th style="text-align:right"> <label for="id_{{ field.name }}">{{ field.label }}{% if field.field.required %}<span class="required"><sup>*</sup></span>{% endif %}</label> </th> <td>{{ field }} {% if field.help_text %} <p class="helptext">({{ field.help_text }})</p> {% endif %} </td> </tr>

 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
from django import newforms as forms
from django.conf import settings
from django.newforms.forms import BoundField, pretty_name
from django.newforms import widgets, fields
from django.template import Context, loader
from nidvid.utils import output_debug

class TemplatedForm(forms.Form):
    def as_template(self):
        "Helper function for fieldsting fields data from form."
        bound_fields = [BoundField(self, field, name) for name, field in self.fields.items()]
        c = Context(dict(form = self, bound_fields = bound_fields))
        # TODO: check for template ... if template does not exist
        # we could just get_template_from_string to some default
        # or we could pass in the template name ... whatever we want
        t = loader.get_template('newforms/form.html')
        return t.render(c)
    
    def as_custom(self):
        "Returns this form rendered as HTML <tr>s -- excluding the <table></table>."

        normal_row = u'<tr><td></td><td>%(errors)s</td></tr><tr><th style="text-align:right">%(label)s</th><td>%(field)s%(help_text)s</td></tr>'
        
        return self._html_output(
            normal_row,
            u'<tr><td colspan="2">%s</td></tr>',
            '</td></tr>',
            u'<br />%s',
            False)
    
    def as_readonly_table(self):
        output = ['<table class="readonly_forms_table">']
        for name, field in self.fields.items():
            data = ""
            label = ""
            if not self.is_bound:
                data = self.initial.get(name, field.initial)
                if callable(data):
                    data = data()
            else:
                # TODO see BoundField in django trunk
                data = field.widget.value_from_datadict(self.data, self.files, name)
                
            # Finally try one more methed to get the data
            if not data and hasattr(self, 'cleaned_data'):
                data = self.cleaned_data[name]
        
            if field.label is None:
                label = pretty_name(name)
            else:
                label = field.label
                
            label = label.strip(':')
            data = data or ""
                
            output.append('<tr><th>%s:</th><td>%s</td></tr>' % (label, data))
                
        output.append('</table>')
        return u'\n'.join(output)
    
    def __str__(self):
        return self.as_template()

More like this

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

Comments

Please login first before commenting.