私はfirst_name
とlast_name
というフィールドを持つモデルを持っていて、これはImageField
にファイル名を作るために使われます。 ImageField
のupload_to
の引数は、このインスタンスの情報でファイル名を生成するこのメソッドです。Djangoモデルのインスタンスを保存しているとき、ModelField属性として使用されているメソッドに対して、clean()とsave()のオーバーライドがどのような順序で適用されますか?
このモデルインスタンスを保存すると、ファイル名の生成に使用される前に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')