This is the best solution I've come up with so far:
class ConfirmForm(forms.Form):
"""
This behaves as a regular form, except that any field
whose name starts with "confirm_" will have an additional
clean method implemented for it that will check its value
against the field of the given name.
For instance, a form with the field 'confirm_password' will
have a 'clean_confirm_password' method added that will
validate that the contents are equal to the 'password' field.
"""
def __init__(self, *args, **kwargs):
super(ConfirmForm,self).__init__(*args,**kwargs)
for name in self.fields.keys():
if name.startswith('confirm_'):
compare_field = name.replace('confirm_','')
setattr(self,'clean_%s' % name,
self._make_confirmation_method(compare_field,
name))
def _make_confirmation_method(self, field_name,
confirm_field_name):
return lambda: self._confirm_fields_match(field_name,
confirm_field_name)
def _confirm_fields_match(self, field_name, confirm_field_name):
if self[field_name].data != self[confirm_field_name].data:
raise ValidationError('This field must match the %s field'
\
% self[field_name].label)
return self.clean_data.get(confirm_field_name)
Now you can have forms like this:
class JoinForm(AwareForm):
email = forms.EmailField()
confirm_email = forms.EmailField()
password =
forms.CharField(widget=PasswordInput(render_value=False))
confirm_password =
forms.CharField(widget=PasswordInput(render_value=False))
Thoughts?
On Mar 16, 4:51 pm, "Ian" <ian.terr...@gmail.com> wrote:
> I brought up a discussion on this topic in the Users' list:
http://groups.google.com/group/django-users/browse_thread/thread/9858...
> To recap the focus of my point:
> > The purpose of web development frameworks is to make common web
> > development tasks easier, or give them to you for free. A forms
> > framework which requires custom code for password comparisons does not
> > satisfy this fundamental requirement.
> I proposed two architectural possibilities: 1) let fields know about
> their BoundFields (or the form itself) so that they can do the
> confirmation at field level, or 2) have additional form functionality
> that knows how to confirm proper fields at the form level. Naive
> implementations of both are present in the other thread.
> (There's a second issue aside from confirmation that option 1 solves:
> any validation that could be done if the field knew its name. In the
> other thread I have an example of a field named "username" that checks
> that it is unique against the "username" column of a class. This is
> more trivial, though, since the column as well as the class could be
> passed to the field.)
> I'm curious to know everyone's thoughts.
> Thanks,
> Ian