Search code examples
pythondjangodjango-modelsimage-uploadingdjango-generic-relations

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. 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.


Solution

  • 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