必须调用模型清洗(这不是自动的),因此请self.full_clean()
在保存方法中放置一些模型清洗。http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean
对于您的表单,您需要返回剥离后的清理数据。
return self.cleaned_data['name'].strip()
我以某种方式认为您只是尝试做一堆行不通的事情。请记住,表单和模型是两件截然不同的东西。
查看有关如何验证表单的表单文档http://docs.djangoproject.com/en/dev/ref/forms/validation/
super(Employee), self.clean().strip() makes no sense at all!
这是您的固定代码:
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()