[英]Django Image model with dynamic upload_to function using generic relation
I am creating an Image model which will be used by other models via generic relation. 我正在创建一个Image模型,其他模型将通过泛型关系使用它。 For example, Newsposts and events will have images. 例如,Newsposts和事件将有图像。 Below is the sample Image model 下面是示例图像模型
class Image(models.Model):
description = models.CharField(max_length=500, null=True, blank=True)
image = models.ImageField(upload_to=get_storage_path)
content_type=models.ForeignKey(ContentType,on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
This will store the image in only one directory. 这会将图像存储在一个目录中。 However the problem is I cannot figure out how can I write a dynamic upload_to
function that will store the images in the corresponding directories, eg images/news/
and images/events
. 然而问题是我无法弄清楚如何编写动态upload_to
函数,将图像存储在相应的目录中,例如images/news/
和images/events
。
The upload_to
handler takes two arguments , instance
and filename
. upload_to
处理程序有两个参数 , instance
和filename
。 You can inspect the instance
to find out which content type the object is associated with: 您可以检查instance
以找出与该对象关联的内容类型:
def get_storage_path(instance, filename):
# This is just an example - you'll need to use the right name
# depending on the model class.
if instance.content_type.model == 'news':
# Generate filename here
else:
# Generate different file name here
If you need to save one file at several locations: Checkout Django Custom Storages . 如果您需要在多个位置保存一个文件:Checkout Django Custom Storages 。
If you just need to set the upload_to folder dynamically according to the related object: Here is a possible duplicate thread which answers your question. 如果您只需要根据相关对象动态设置upload_to文件夹: 这是一个可能的重复线程,它可以回答您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.