How do I strip whitespaces (trim) from the end of a charField in Django?
Here is my Model, as you can see I've tried putting in clean methods but these never get run.
I've also tried doing name.strip()
, models.charField().strip()
but these do not work either.
Is there a way to force the charField to trim automatically for me?
Thanks.
from django.db import models
from django.forms import ModelForm
from django.core.exceptions import ValidationError
import datetime
class Employee(models.Model):
"""(Workers, Staff, etc)"""
name = models.CharField(blank=True, null=True, max_length=100)
def save(self, *args, **kwargs):
try:
# This line doesn't do anything??
#self.full_clean()
Employee.clean(self)
except ValidationError, e:
print e.message_dict
super(Employee, self).save(*args, **kwargs) # Real save
# If I uncomment this, I get an TypeError: unsubscriptable object
#def clean(self):
# return self.clean['name'].strip()
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural = 'Employees'
class Admin:pass
class EmployeeForm(ModelForm):
class Meta:
model = Employee
# I have no idea if this method is being called or not
def full_clean(self):
return super(Employee), self.clean().strip()
#return self.clean['name'].strip()
Edited: Updated code to my latest version. I am not sure what I am doing wrong as it's still not stripping the whitespace (trimming) the name field.
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):
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:
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:
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.
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 forms http://docs.djangoproject.com/en/dev/ref/forms/validation/
super(Employee), self.clean().strip() makes no sense at all!
Here's your code fixed:
I'm handling this in views as a decorator. I'm also truncating field values that exceed a CharField max_length value.
If you have so many data-fields to be trimmed, why not try extending CharField?
UPDATE: For Django versions <= 1.7 if you want to extend field, you are to use models.SubfieldBase metaclass. So here it will be like:
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
If you're still not on Django 1.9+ shame on you (and me) and drop this into your form. This is similar to @jeremy-lewis's answer but I had several problems with his.