Login

Custom Form Example: Forms for Bootstrap Html - CSS Toolkit

Author:
fatiherikli
Posted:
December 16, 2011
Language:
Python
Version:
1.3
Score:
3 (after 3 ratings)

Improved for BootStrap details: http://twitter.github.com/bootstrap/

Using:

class AnyForm(forms.Form, CustomForm): pass

Template:

<form> {{ form.render_errors }} {{ form.as_div }} </form>

 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
# -*- coding:utf-8 -*-
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _


class CustomForm(object):
    """
    Inherit with forms.Form or forms.ModelForm
    For example:
        class AnyForm(forms.Form, CustomForm):
            pass

        class AnyModelForm(forms.ModelForm, CustomForm):
            pass
    """
    def render_errors(self):
        if not self.errors:
            return ""
        output = []
        output.append(u'<div class="alert-message block-message error">')
        output.append(u'<a class="close" href="#">×</a>')
        output.append(u'<p><strong>%s</strong></p><ul>' % _('You got an error!'))
        for field, error in self.errors.items():
            output.append(u'<li><strong>%s</strong> %s</li>' % (field.title(), error[0]))
        output.append(u'</ul></div>')
        return mark_safe(u'\n'.join(output))


    def as_div(self):
        output = []
        for boundfield in self: #see original Form class __iter__ method
            row_template = u'''
            <div class="clearfix %(div_class)s">
                %(label)s
                <div class="input">
                    %(field)s
                    <span class="help-block">%(help_text)s </span>
                </div>
            </div>
            '''
            row_dict = {
                "div_class" : "",
                "required_label" : "",
                "field" : boundfield.as_widget(),
                "label" : boundfield.label_tag(),
                "help_text" : boundfield.help_text,
            }

            if boundfield.errors:
                row_dict["div_class"] = "error"
                boundfield.field.widget.attrs["class"]="error"

            output.append(row_template % row_dict)
        return mark_safe(u'\n'.join(output))

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.