On Thu, Jul 14, 2011 at 10:35 PM, Luke Plant <l.plant...@cantab.net> wrote:
> On 10/07/11 22:26, Chris Beaven wrote:
>> To clarify, didn't even notice we were talking about models.Field, I'm
>> +0 for a 'strip' attribute on the form's field, nothing on the model.
>
> Like Chris, I don't think we can put this feature anywhere on model
> definition. It is clearly an issue of how a form should be processed,
> not an issue of what data can exist in the model. strip=True means "when
> receiving input from user, strip leading/trailing whitespace" - and
> something similar for any 'text_filter' attribute. That really cannot
> belong on a field definition.
>
> With that said, the next option because an option on form fields. This
> isn't particularly attractive to me, because for ModelForm it isn't
> going to be automatically applied (for the reasons Jacob has given), and
> now you need some fairly hacky or non-DRY way to specify it.
>
> My solution to date has been this form mixin that need it:
>
> class StripStringsMixin(object):
>    def clean(self):
>        for field,value in self.cleaned_data.items():
>            if isinstance(value, basestring):
>                self.cleaned_data[field] = value.strip()
>        return self.cleaned_data
>
> This mixin is easy to use - just add it to a form's base class. This is
> even still easy to use in the context of the admin. Although this may
> not be perfect, it's probably the least of all the various evils.
>
> Luke
>

That would strip whitespace from every field. I suppose it could be
specialized from the meta class..

Specializing automatically generated fields in model forms is pretty
common when you want to specialize their behaviour, for example if you
wish to use a different widget for a field, or if you want to provide
a custom label.

I don't see why this is considered hacky or anti-DRY.

Eg:

class FooForm(forms.ModelForm, StripWhiteSpaceMixin):
  class Meta:
    strip_whitespace_fields = ( 'username', )
    model = Foo

or

class FooForm(forms.ModelForm):
  username = forms.CharField(strip_whitespace=True)
  class Meta:
    model = Foo

So much discussion over one tiny form field normalization.

Cheers

Tom

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

Reply via email to