4

I am creating an Image model which will be used by other models via generic relation. For example, Newsposts and events will have images. 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, e.g images/news/ and images/events.

grustamli
  • 305
  • 3
  • 12

2 Answers2

2

The upload_to handler takes two arguments, instance and filename. You can inspect the instance to find out which content type the object is associated with:

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
solarissmoke
  • 27,879
  • 12
  • 62
  • 68
1

If you need to save one file at several locations: 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.

Tobias Ernst
  • 3,488
  • 1
  • 28
  • 26