如何从django的charfield结尾处去除空白(trim)?
这是我的模型,正如你所看到的,我尝试过使用干净的方法,但这些方法永远不会运行。
我也试过这样做,但这些都不起作用。
有没有办法强迫charfield自动为我修剪?
谢谢。

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

已编辑:已将代码更新为我的最新版本。我不确定我做错了什么,因为它仍然没有去除空白(修剪)名称字段。

最佳答案

必须调用模型清理(它不是自动的),所以在保存方法中放置一些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()

关于python - (Django)修剪charField的空格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5043012/

10-12 14:18