Login

Custom Form Example: Forms for Bootstrap Html - CSS Toolkit

Author:
fatiherikli
Posted:
December 16, 2011
Language:
Python
Version:
1.3
Tags:
forms bootstrap twitter modelform as_div
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. Bootstrap button dropdown widget (replaces forms.Select) by benjaoming 2 years, 9 months ago
  2. load m2m fields objects by dirol 4 years, 11 months ago
  3. boostrap prepend-input for widgets by DimmuR 2 years, 7 months ago
  4. boostrap append-input for widgets by DimmuR 2 years, 7 months ago
  5. Form splitting/Fieldset templatetag by peritus 6 years, 8 months ago

Comments

Please login first before commenting.