栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

(Django)从charField修剪空格

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639587.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号