我需要为上传的图片定义自定义文件名,我有这个模型:
class Personas(model.Models):
... some fields here ...
documento = models.CharField(max_length=10)
class Identificacion(model.Models):
...some fields here...
persona = models.ForeignKey('Personas')
fotos = models.ManyToManyField('FotoPersona',related_name='foto_persona',blank=True,null=True)
class FotoPersona(model.Models):
persona = models.ForeignKey('Personas')
foto = models.ImageField(upload_to= CUSTOM_PATH)
CUSTOM_PATH必须采用下一种格式:
APP_NAME / persona.documento / FILE_NAME
其中file_name可以是:
PERFIL
阵线
cuerpo_entero
我该怎么做?
答案 0 :(得分:1)
您可以定义将构建所需文件名的函数,并在ImageField的upload_to参数中使用它:
def upload_name(instance, filename):
return '{}/{}/{}'.format(app_name, instance.persona.documento, filename)
class FotoPersona(model.Models):
persona = models.ForeignKey('Personas')
foto = models.ImageField(upload_to=upload_name)