python - 如何在django中使用upload_to指定目录和函数

标签 python django image-upload file-storage

我有 2 款汽车和配置文件:

class Car(models.Model):
    name = models.CharField(max_length=200)
    image_file = models.ImageField(upload_to=naming, null=True, blank=True)

class Profile(models.Model):
    name = models.CharField(max_length=200)
    image_file = models.ImageField(upload_to='profiles', null=True, blank=True)

我需要命名功能,但我也希望上传的文件位于 cars 文件夹中,而不仅仅是媒体目录中。

有什么方法可以将它们上传到该文件夹​​并调用该函数吗? 在 doc我只能找到一种方法,但不能同时找到两种方法。

提前致谢!

最佳答案

我不明白你说的同时上传和调用该函数是什么意思,但是该函数确实被调用了,否则不会产生任何路径。对于您的第一个问题,您可以执行以下操作:

def naming(instance, file_name):                                                 
    model_name = instance.__class__.__name__
    return os.path.join(model_name, file_name)

关于python - 如何在django中使用upload_to指定目录和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33136337/

相关文章:

python - 谷歌应用引擎: reverse reference lookups

php - 将带有缩略图的图像上传到文件夹并添加到 Mysql 的路径

python - wagtail rawhtmlblock 错误?

python - 使用 Python 在注册表运行键中创建新值?

python - 我的 Python 凯撒密码程序在 30 后停止移动

django - 基于类的 View 和脚本调用函数

python - 保留一列的首选值并删除不太首选的值

python - Django:使用 related_name 添加引用同一个表的 2 个外键导致 NameError - 未定义给定相关名称的值

php - MySQL:更新(不上传图像)

javascript - Dropzone.js - 显示存储在 app_data 文件夹中的图像