Just revisiting this thread...

On 9/14/07, Doug B <[EMAIL PROTECTED]> wrote:
>
> I think you can make a custom form field to do your validation check
> for you.
>
> def StrippedField(forms.CharField):
>     def clean(self,value):
>         #do your validation here

While the solution above would work and I have been using that as
well, I found that there were times that I needed to perform some
post-validation stuff on the field data. The fields would be of
different types but the post-validation operations would be the same.
I did not find it entirely appealing to have to create an entire set
of subclasses to do this, i.e.:

SpecialCharField(forms.CharField)
SpecialBooleanField(forms.BooleanField)
etc...

or the alternative way by using clean_FIELDNAME()

So I was looking for a more generic way of iterating through all or
selected fields and applying a method that modifies their contents.

After looking around a bit in ASPN, I decided to go with a method factory:

class StrippedFieldsForm(forms.Form):
    stripped_fields = []
    def __init__(self, *args, **kwargs):
        super(StrippedFieldsForm, self).__init__(*args, **kwargs)
        for name in self.fields:
            setattr(StrippedFieldsForm, 'clean_%s' % name,
self.clean_field_factory(name))

    def clean_field_factory(self, name):
        def _strip_field(self):
            field = self.fields[name]
            label = self.fields[name].label or name
            return self.strip_field(name, label + ' is empty.')
        return _strip_field

    def strip_field(self, field, error_message):
        if (self.clean_data.get(field)):
            data = self.clean_data[field].strip()
            if (0 == len(data)):
                raise forms.ValidationError(error_message)
            else:
                return data
        else:
            return ''

It looks like a lot of work to implement and seems sort of pointless
as I'm sure that the subclass way is preferred in most cases. But in
my case, I needed to be able to swap out strip_field() with something
else on a case-by-case basis. As always, am open to using a better
solution, but for the moment this works for me. Hope someone finds
this useful.
-- 
_nimrod_a_abing_

http://abing.gotdns.com/
http://www.preownedcar.com/

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to