(Django) Trim whitespaces from charField (Django) Trim whitespaces from charField python python

(Django) Trim whitespaces from charField


When you're using a ModelForm instance to create/edit a model, the model's clean() method is guaranteed to be called. So, if you want to strip whitespace from a field, you just add a clean() method to your model (no need to edit the ModelForm class):

class Employee(models.Model):    """(Workers, Staff, etc)"""    name = models.CharField(blank=True, null=True, max_length=100)    def clean(self):        if self.name:            self.name = self.name.strip()

I find the following code snippet useful- it trims the whitespace for all of the model's fields which subclass either CharField or TextField (so this also catches URLField fields) without needing to specify the fields individually:

def clean(self):    for field in self._meta.fields:        if isinstance(field, (models.CharField, models.TextField)):            value = getattr(self, field.name)            if value:                setattr(self, field.name, value.strip())

Someone correctly pointed out that you should not be using null=True in the name declaration. Best practice is to avoid null=True for string fields, in which case the above simplifies to:

def clean(self):    for field in self._meta.fields:        if isinstance(field, (models.CharField, models.TextField)):            setattr(self, field.name, getattr(self, field.name).strip())


Model cleaning has to be called (it's not automatic) so place some self.full_clean() in your save method.
http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean

As for your form, you need to return the stripped cleaned data.

return self.cleaned_data['name'].strip()

Somehow I think you just tried to do a bunch of stuff that doesn't work. Remember that forms and models are 2 very different things.

Check up on the forms docs on how to validate formshttp://docs.djangoproject.com/en/dev/ref/forms/validation/

super(Employee), self.clean().strip() makes no sense at all!

Here's your code fixed:

class Employee(models.Model):    """(Workers, Staff, etc)"""    name = models.CharField(blank=True, null=True, max_length=100)    def save(self, *args, **kwargs):        self.full_clean() # performs regular validation then clean()        super(Employee, self).save(*args, **kwargs)    def clean(self):        """        Custom validation (read docs)        PS: why do you have null=True on charfield?         we could avoid the check for name        """        if self.name:             self.name = self.name.strip()class EmployeeForm(ModelForm):    class Meta:        model = Employee    def clean_name(self):        """        If somebody enters into this form ' hello ',         the extra whitespace will be stripped.        """        return self.cleaned_data.get('name', '').strip()


Django 1.9 offers a simple way of accomplishing this. By using the strip argument whose default is True, you can make sure that leading and trailing whitespace is trimmed. You can only do that in form fields though in order to make sure that user input is trimmed. But that still won't protect the model itself. If you still want to do that, you can use any of the methods above.

For more information, visit https://docs.djangoproject.com/en/1.9/ref/forms/fields/#charfield