【发布时间】:2012-04-15 19:13:57
【问题描述】:
我有一个带有first_name 和last_name 字段的模型,它们用于在ImageField 上创建文件名。 ImageField 上的 upload_to 的参数是使用此实例信息生成文件名的此方法。
当这个模型实例被保存时,在clean() 中对.strip() 的调用是否会在用于生成文件名之前应用于字段?或者我是否需要在使用数据时以及在清理时对数据执行.strip()?
models.py:
def set_path(instance, filename):
"""
Set the path to be used for images uploaded (trainer photos).
"""
return u'about/%(first)s_%(last)s.%(ext)s' % {
'first': instance.first_name.strip(' \t').lower(), #.strip() required?
'last': instance.last_name.strip(' \t').lower(), #.strip() required?
'ext': filename.split('.')[-1]
}
class Trainer(models.Model):
"""
Trainers and their associated information.
"""
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
image = models.ImageField(upload_to=set_path, blank=True, null=True,
verbose_name="Trainer image")
description = models.TextField()
class Meta:
unique_together = ('first_name', 'last_name',)
def clean(self):
super(Trainer, self).clean()
# Are these calls to .strip() applied before the fields
# get used as `instance` to determine a filename?
self.first_name = self.first_name.strip(' \t')
self.last_name = self.last_name.strip(' \t')
self.description = self.description.strip(' \t\r\n')
【问题讨论】:
标签: django django-models save