zar*_*don 16 python django django-models removing-whitespace
如何从Django中的charField末尾删除空格(trim)?
这是我的模型,你可以看到我已经尝试过使用干净的方法,但这些方法永远不会运行.
我也尝试过name.strip()
,models.charField().strip()
但这些都不起作用.
有没有办法强制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()
Run Code Online (Sandbox Code Playgroud)
编辑:更新了我最新版本的代码.我不确定我做错了什么,因为它仍然没有剥离空白(修剪)名称字段.
Jer*_*wis 21
当您使用ModelForm实例创建/编辑模型时,可以保证调用模型的clean()方法.因此,如果要从字段中删除空格,只需向模型添加clean()方法(无需编辑ModelForm类):
class Employee(models.Model):
"""(Workers, Staff, etc)"""
name = models.CharField(blank=True, null=True, max_length=100)
def clean(self):
if self.name:
self.name = self.name.strip()
Run Code Online (Sandbox Code Playgroud)
我发现以下代码片段很有用 - 它修剪了所有模型字段的空白,这些字段是CharField或TextField的子类(因此这也捕获了URLField字段),而无需单独指定字段:
def clean(self):
for field in self._meta.fields:
if isinstance(field, (models.CharField, models.TextField)):
value = getattr(self, field.name)
if value:
setattr(self, field.name, value.strip())
Run Code Online (Sandbox Code Playgroud)
有人正确地指出你不应该在名称声明中使用null = True.最佳做法是避免字符串字段为null = True,在这种情况下,上述内容简化为:
def clean(self):
for field in self._meta.fields:
if isinstance(field, (models.CharField, models.TextField)):
setattr(self, field.name, getattr(self, field.name).strip())
Run Code Online (Sandbox Code Playgroud)
Yuj*_*ita 11
必须调用模型清理(它不是自动的),所以self.full_clean()
在你的保存方法中放置一些.
http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean
至于表单,您需要返回已剥离的已清理数据.
return self.cleaned_data['name'].strip()
Run Code Online (Sandbox Code Playgroud)
不知何故,我认为你只是试图做一堆不起作用的东西.请记住,表单和模型是两个非常不同的东西.
查看有关如何验证表单的表单文档 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()
Run Code Online (Sandbox Code Playgroud)
Django 1.9 提供了一种简单的方法来实现这一点。通过使用strip
默认为 True的参数,您可以确保修剪前导和尾随空格。您只能在表单字段中执行此操作,以确保修剪用户输入。但这仍然不能保护模型本身。如果您仍然想这样做,您可以使用上述任何一种方法。
有关更多信息,请访问https://docs.djangoproject.com/en/1.9/ref/forms/fields/#charfield
如果要修剪这么多数据字段,为什么不尝试扩展CharField?
from django.db import models
from django.utils.translation import ugettext_lazy as _
class TrimCharField(models.CharField):
description = _(
"CharField that ignores leading"
" and trailing spaces in data")
def get_prep_value(self, value)
return trim(super(TrimCharField, self
).get_prep_value(value))
def pre_save(self, model_instance, add):
return trim(super(TrimCharField, self
).pre_save(model_instance, add))
Run Code Online (Sandbox Code Playgroud)
更新:对于Django版本<= 1.7,如果你想扩展字段,你将使用models.SubfieldBase元类.所以这里会是这样的:
class TrimCharField(six.with_metaclass(
models.SubfieldBase, models.CharField)):
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25782 次 |
最近记录: |