(Django)从charField修剪空格

(Django)从charField修剪空格,第1张

(Django)从charField修剪空格

必须调用模型清洗(这不是自动的),因此请

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()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/5645394.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存