您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

(Django)从charField修剪空格

(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()
Go 2022/1/1 18:36:16 有458人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶