(Django)从charField修剪空格 [英] (Django) Trim whitespaces from charField

查看:141
本文介绍了(Django)从charField修剪空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Django中的charField结尾处移除空格(trim)?

How do I strip whitespaces (trim) from the end of a charField in Django?

这是我的模型,你可以看到我已经尝试了干净的方法,但这些永远不会运行。

Here is my Model, as you can see I've tried putting in clean methods but these never get run.

我也尝试过 name.strip() models.charField()。strip()但这些也不起作用。

I've also tried doing name.strip(), models.charField().strip() but these do not work either.

有没有办法强制使用charField为我自动修剪?

Is there a way to force the charField to trim automatically for me?

感谢。

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

已编辑:已更新代码到我的最新版本。我不知道我做错了什么,因为它仍然没有剥离空白(修剪)名称字段。

Edited: Updated code to my latest version. I am not sure what I am doing wrong as it's still not stripping the whitespace (trimming) the name field.

推荐答案

模型清理必须被调用(不是自动的),所以在你的保存方法中放置一些 self.full_clean()

http://docs.djangoproject.com/en/dev/ref/模型/实例/#django.db.models.Model.full_clean

Model cleaning has to be called (it's not automatic) so place some self.full_clean() in your save method.
http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean

对于您的表单,您需要返回剥离的清理数据。

As for your form, you need to return the stripped cleaned data.

return self.cleaned_data['name'].strip()

不知怎的,我想你只是试图做一堆不起作用的东西。请记住,表单和模型是两个非常不同的东西。

Somehow I think you just tried to do a bunch of stuff that doesn't work. Remember that forms and models are 2 very different things.

检查表单文档如何验证表单
http://docs.djangoproject.com/en/dev/ref/forms/validation/

Check up on the forms docs on how to validate forms http://docs.djangoproject.com/en/dev/ref/forms/validation/

super(Employee),self.clean()。strip()完全没有意义!

这是您的代码修复:

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

这篇关于(Django)从charField修剪空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆