WTForm is an extension to the django newforms library allowing the developer, in a very flexible way, to layout the form fields using fieldsets and columns
WTForm was built with the well-documented YUI Grid CSS in mind when rendering the columns and fields. This should make it easy to implement WTForm in your own applications.
Here is an image of an example form rendered with WTForm.
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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | '''
WTForm (What The Form)
======================
WTForm is an extension to the django newforms library allowing
the developer, in a very flexible way, to layout the form
fields using <fieldset>s and columns
WTForm was built with the well-documented YUI Grid CSS[1] in
mind when rendering the columns and fields. This should make
it easy to implement WTForm in your own applications.
Revision history
----------------
0.1 (May 2007) - Initial release
0.2 (August 2007) - Bugfix release
WTForm now works with form_for_model and form_for_instance
(see "Using forms_for_model and form_for_instance" for details)
Specifying the form layout
--------------------------
WTForm will look for a subclass of your form called "Meta". This
class should have a tuple variable called layout . The layout
variable will hold a tree structure of fields, field sets and
columns.
Here is a simple example:
class MyForm(WTForm):
name = forms.CharField(label="Name")
email = forms.EmailField(label="E-mail address")
class Meta:
layout = (Columns(("name",), ("email",)),)
This will result in the form layout of:
+--------------------------+--------------------------+
| Name | E-mail address |
| [______________________] | [______________________] |
+--------------------------+--------------------------+
WTForm currently uses four types of nodes (fields):
- Fieldset(legend, field[, field])
Represents a HTML <fieldset> with the fields specified
by the arguments as contents. The first argument will
be the content of the <legend> HTML node. If the legend
argument is the empty string, the <legend> HTML node
will not be rendered.
- Columns(column[, column] [, css_class="foobar"])
Represents a column grid. The columns are specified as
tuples of fields. In order to obtain different grid
sizes, the Columns function takes an optional keyword
argument called css_class which will be rendered as the
class of the outer-most <div> of the grid layout.
See the YUI Grid CSS specification[1] for details on
possible values for css_class. Also, see the
"Columns CSS styling" part of this documentation.
Even if you only have one field per column, remember
to pass a tuple to the Columns function:
Columns(("field1",), ("field2",))
- HTML(content)
Represents HTML content. This is useful for embedding
HTML pieces in between fields for documentation. This
type of node has no children.
- "name"
A string represents a single field. The field must be
defined in your form. If the field could not be
resolved, the NoSuchFormField exception will be raised.
Columns and Fieldset nodes can be nested as deep as you
want (just as long as you dont get in a fight with your web
designer).
More examples:
--------------
If you need to add two individuals in your form, you could put
them in field sets:
class MyForm(WTForm):
name1 = forms.CharField(label="Name (1)")
email1 = forms.EmailField(label="E-mail address (1)")
name2 = forms.CharField(label="Name (2)")
email2 = forms.EmailField(label="E-mail address (2)")
class Meta:
layout = (Fieldset("Person 1",
Columns(("name1",), ("email1",))),
Fieldset("Person 2",
Columns(("name2",), ("email2",))))
This will result in the form layout of:
+-[ Person 1 ]----------------------------------------+
|+-------------------------+-------------------------+|
|| Name (1) | E-mail address (1) ||
|| [_____________________] | [_____________________] ||
|+-------------------------+-------------------------+|
+-----------------------------------------------------+
+-[ Person 2 ]----------------------------------------+
|+-------------------------+-------------------------+|
|| Name (2) | E-mail address (2) ||
|| [_____________________] | [_____________________] ||
|+-------------------------+-------------------------+|
+-----------------------------------------------------+
Say you would like one big field set with the charfields in
two columns:
class MyForm(WTForm):
name1 = forms.CharField(label="Name (1)")
email1 = forms.EmailField(label="E-mail address (1)")
name2 = forms.CharField(label="Name (2)")
email2 = forms.EmailField(label="E-mail address (2)")
class Meta:
layout = (Fieldset("Person details",
Columns(("name1", "name2"),
("email1", "email2"))),)
This will result in the form layout of:
+-[ Person details ]----------------------------------+
|+-------------------------+-------------------------+|
|| Name (1) | E-mail address (1) ||
|| [_____________________] | [_____________________] ||
|| | ||
|| Name (2) | E-mail address (2) ||
|| [_____________________] | [_____________________] ||
|+-------------------------+-------------------------+|
+-----------------------------------------------------+
Columns CSS styling:
--------------------
The Column HTML is written with the intent of working with
the YUI CSS for grids. When using Columns you can specify
the CSS class of the outer <div> by supplying the keyword
argument css_class:
Columns(field1, field2, field3, css_class="yui-gc")
This will create a 2/3 - 1/3 grid with two columns. Read
more about YUI Grids CSS:
http://developer.yahoo.com/yui/grids/
Differences from newforms / HTML structure of fields:
-----------------------------------------------------
In order to make CSS styling a lot easier, WTForm til raise
NotImplemented on as_table, as_p and as_ul. When rendering
WTForm forms you must use as_div, as we believe that this
is the way to structure your forms.
A field will be rendered as:
<div class="CharField TextInput">
<label for="id_name">Name</label>
<span class="help_text">Very helpful text</span>
<ul class="errors">
<li>Error 1</li>
<li>Error 2</li>
</ul>
<div class="field">
<input type="text" name="name" value="" id="id_name" />
</div>
</div>
The CSS classes in the outer <div> is fetched from the field
type as well as the widget type. If the field is marked as
required - it will also get a Required.
Data handling / newforms compability:
-------------------------------------
WTForm descends from newforms.BaseForm, thus data handling is
done the same way: is_valid(), clean_data...
Refer to the newforms documentation[2] for details.
Using forms_for_model and form_for_instance
-------------------------------------------
When using form_for_model, you only need to define the layout
of the form. Here is an example from our Intranet application:
from django import newforms as forms
from intranet.timesheet.models import TimeEntry
from wtform import WTForm, Fieldset
class TimeEntryFormBase(WTForm):
class Meta:
layout = (Fieldset('Elements',
'employee', 'date', 'project',
'description', 'tickets'),)
TimeEntryForm = forms.form_for_model(TimeEntry,
form=TimeEntryFormBase)
As well as:
TimeEntryForm = forms.form_for_instance(entry,
form=TimeEntryFormBase)
Again, for details about form_for_model and form_for_instance,
you should refer to the newforms documentation[2] at the django
website.
Credits:
--------
Christian Joergensen <christian.joergensen [at] gmta.info>
Oscar Eg Gensmann <oscar.gensmann [at] gmta.info>
Founded in 2003, GMTA ApS is the partnership between three
danish computer enthusiasts with a strong interest in the
web-phenomenon.
Visit our website: http://www.gmta.info
License:
--------
Creative Commons Attribution-Share Alike 3.0 License
http://creativecommons.org/licenses/by-sa/3.0/
When attributing this work, you must maintain the Credits
paragraph above.
References:
-----------
[1] http://developer.yahoo.com/yui/grids/
[2] http://www.djangoproject.com/documentation/newforms/
'''
from django.newforms.forms import BoundField
from django.utils.html import escape
from django.newforms import BaseForm
class NoSuchFormField(Exception):
"The form field couldn't be resolved."
pass
def error_list(errors):
return '<ul class="errors"><li>' + \
'</li><li>'.join(errors) + \
'</li></ul>'
class WTForm(BaseForm):
def __init__(self, data=None, auto_id='id_%s', prefix=None, initial=None):
super(WTForm, self).__init__(data, auto_id, prefix, initial)
# do we have an explicit layout?
if hasattr(self, 'Meta') and hasattr(self.Meta, 'layout'):
self.layout = self.Meta.layout
else:
# Construct a simple layout using the keys from the fields
self.layout = self.fields.keys()
self.prefix = []
self.top_errors = []
def as_table(self):
raise NotImplementedError("WTForm does not support <table> output.")
def as_ul(self):
raise NotImplementedError("WTForm does not support <ul> output.")
def as_p(self):
raise NotImplementedError("WTForm does not support <p> output.")
def as_div(self):
''' Render the form as a set of <div>s. '''
output = self.render_fields(self.layout)
prefix = u''.join(self.prefix)
if self.top_errors:
errors = error_list(self.top_errors)
else:
errors = u''
self.prefix = []
self.top_errors = []
return prefix + errors + output
# Default output is now as <div> tags.
__str__ = as_div
def render_fields(self, fields, separator=u""):
''' Render a list of fields and join the fields by
the value in separator. '''
output = []
for field in fields:
if isinstance(field, (Columns, Fieldset, HTML)):
output.append(field.as_html(self))
else:
output.append(self.render_field(field))
return separator.join(output)
def render_field(self, field):
''' Render a named field to HTML. '''
try:
field_instance = self.fields[field]
except KeyError:
raise NoSuchFormField("Could not resolve form field '%s'." % field)
bf = BoundField(self, field_instance, field)
output = ''
if bf.errors:
# If the field contains errors, render the errors to a <ul>
# using the error_list helper function.
bf_errors = error_list([escape(error) for error in bf.errors])
else:
bf_errors = ''
if bf.is_hidden:
# If the field is hidden, add it at the top of the form
self.prefix.append(unicode(bf))
# If the hidden field has errors, append them to the top_errors
# list which will be printed out at the top of form
if bf_errors:
self.top_errors.extend(bf.errors)
else:
# Find field + widget type css classes
css_class = type(field_instance).__name__ + " " + \
type(field_instance.widget).__name__
# Add an extra class, Required, if applicable
if field_instance.required:
css_class += " Required"
if bf.label:
# The field has a label, construct <label> tag
label = escape(bf.label)
label = bf.label_tag(label) or ''
else:
label = ''
if field_instance.help_text:
# The field has a help_text, construct <span> tag
help_text = escape(field_instance.help_text)
help_text = '<span class="help_text">%s</span>' % help_text
else:
help_text = u''
# Finally render the field
output = '<div class="field %(class)s">%(label)s%(help_text)s%(errors)s<div class="input">%(field)s</div></div>\n' % \
{'class': css_class, 'label': label, 'help_text': help_text, 'errors': bf_errors, 'field': unicode(bf)}
return output
class Fieldset(object):
''' Fieldset container. Renders to a <fieldset>. '''
def __init__(self, legend, *fields):
self.legend_html = legend and ('<legend>%s</legend>' % legend) or ''
self.fields = fields
def as_html(self, form):
return u'<fieldset>%s%s</fieldset>' % \
(self.legend_html, form.render_fields(self.fields))
class Columns(object):
''' Columns container. Renders to a set og <div>s named
with classes as used by YUI (Yahoo UI) '''
def __init__(self, *columns, **kwargs):
self.columns = columns
self.css_class = kwargs.has_key('css_class') and kwargs['css_class'] or 'yui-g'
def as_html(self, form):
output = []
first = " first"
output.append('<div class="%s">' % self.css_class)
for fields in self.columns:
output.append('<div class="yui-u%s">%s</div>' % \
(first, form.render_fields(fields)))
first = ''
output.append('</div>')
return u''.join(output)
class HTML(object):
''' HTML container '''
def __init__(self, html):
self.html = html
def as_html(self, form):
return self.html
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Thank you, this is very nice! However, it doesn't seem to work with form_for_model or form_for_instance... the resulting class doesn't have any goodies in it:
#
You're right. I will try to look into this.
Regards,
#
Do you have a URL to a page showing this code in action?
#
jmohr, your issue has now been resolved. The WTForm class now descends directly form BaseForm and that solved the problem.
Thank you.
#
simon, I have added a screenshot to the description.
#
With recent django svn (r5830) I'm seeing a couple of problems:
Without either deriving from forms.Form or adding a
__metaclass__ = django.newforms.forms.DeclarativeFieldsMetaclass"
to the class I see an error about base_fields being missing on the WTForm class when I try to use it.There are some new arguments in the BaseForm class, omitting them seems to break errors, changing the
__init__
to this fixes it:def __init__(self, *args, **kwargs): super(WTForm, self).__init__(*args, **kwargs)
(sorry, can't seem to get indentation working right)
#
the tabindex needs to be set if you use 2 columns... is there a way to automate this?
#
object has no attribute 'base_fields'
I want to clarify mickwomey's comment because I glossed over the first part of what he said and had to do my own debugging.
The WTForm class must be updated to match the following
Note that DeclarativeFieldMetaclass must be imported from django.newforms.forms and NOT django.newforms
I have tested this with django r6063
#
WTForm fails silently with no output
I ran into another problem (user error) when trying to use this great module. I guess I need to start reading more carefully because the answer is in the documentation.
For clarification the layout variable must be a tuple or other iterable object, meaning it has a getitem method.
What annoyed me, was that if you fail to make to do so, there is no warning. The modules just fails silently. It took me close to an hour of debugging to figure out where I had gone wrong.
Example:
This fails silently
This does not
The difference being the comma between the last two parenthesis.
Solution: To avoid this minor detail snagging me again I added a assert statement to the WTForm init method, to ensure that layout is iterable.
I have reprinted the entire method for clarity. Please note that my sample includes the changes first pointed out by micktwomey that are required to make this module compatible with current versions of django.
I have tested this with django r6063
#
Crying shame this isn't maintained.
#
Was able to make it work as of March 08.
#
^ append
Got this working with a lot of hassle made short thanks to the advice of mthorley above. Good work!
One thing you will also have to do is....
from django.utils import safestring
and then for as_div....
return safestring.mark_safe(prefix + errors + output)
#
@subsume:
CAn you explain hox you did it working ? I always have this error: Could not resolve form field 'name'.
My function:
and my Page model:
thanks if you could help me.
#
HI,
#
Oh my, I discareded my version, also in django snippets (which is quiet similar as this approach) long time ago because this damn well should be in django already!
Thumbs up for maintaining! If we could get this to be part of Django distribution (contrib or something), then I for one could try to make django admin use this. I hate the way Django admin does fieldsets.
#
A very nice article to read, and I will share thank you.
#
Please login first before commenting.