(This is rapidly getting outdated, go read the source at http://code.djangoproject.com/browser/django/trunk/django/newforms for the current state…).
Django is getting new form handling code, currently in the module django.newforms but it will migrate to django.forms in a future release. The code is very new and under active development. Here are just some quick notes after browsing the code (r3945).
The newforms package is divided into fields, forms, util, and widgets. Widgets are classes that have a render method that returns the html widget as a unicode string (flatatt is a function that flattens a dictionary):
[sourcecode language=”python”]
class TextInput(Widget):
def render(self, name, value, attrs=None):
if value is None: value = ”
final_attrs = dict(self.attrs, type=’text’, name=name)
if attrs:
final_attrs.update(attrs)
if value != ”: final_attrs[‘value’] = value # Only add the ‘value’ attribute if a value is non-empty.
return u'<input %s />’ % flatatt(final_attrs)
[/sourcecode]
The currently defined widgets include TextInput, Textarea, and CheckboxInput.
Fields are classes encapsulating the validation of input data. They should have constructors that take a widget parameter in addition to captioning validation parameters like max_length etc., and a to_python method that converts an input value to a Python value:
[sourcecode language=”python”]
class MyField(django.newforms.Field):
def __init__(self, …, required=True, widget=None):
# set the widget
super(MyField, self).__init__(self, required, widget)
… save other validation parameters here …
def to_python(self, value):
# validates empty values vs. required fields
super(MyField, self).to_python(value)
… validate value here …
[/sourcecode]
The current field classes include CharField, IntegerField, DateField, DateTimeField, RegexField, EmailField, and BooleanField. The date fields are by default US centric but you can pass a tuple of format strings in the input_formats parameter to suit your local traditions. The django.newforms.util.ValidationErrors that are thrown currently contain English text unless I’m reading the code the wrong way (it’ll probably be internationalized shortly).
Finally the Form class contains a metaclass to allow for convenient declaration of fields
[sourcecode language=”python”]
class MyForm(django.newform.Form):
name = CharField(max_length=35)
dob = DateField(input_formats=[‘%d/%m/%Y’], required=False, widget=TextInput)
…
[/sourcecode]
The field names are available to methods of MyForm in the self.fields dictionary.The default widget is TextInput.