Gautham Kolluru
Gautham Kolluru

Reputation: 99

Django application: the directory_name to which an image has to be uploaded, should be auto populated

I want to upload images to the django server using my application and the folder/directory_name to which the image has to be uploaded, should be auto populated using the foreignkey relationship that my models are sharing

My models classes are as follows,

class Event(models.Model):
    event_name = models.CharField(max_length=200)
    event_desc = models.CharField(max_length=5000)

    def __str__(self):
        return self.event_name
class Image(models.Model):
    event_id = models.ForeignKey(Event, on_delete=models.CASCADE)
    image_name = models.CharField(max_length=200)
    image = models.ImageField(upload_to='events/{}'.format("something"))

    def __str__(self):
        return self.image_name

the something in the models.ImageField function has to be replaced by the event_name dynamically and the value for event_name should be populated dynamically.

Upvotes: 2

Views: 77

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You can pass a callable to the upload_to=… parameter [Django-doc]: which contains a reference to the model object, so you can redefine this to:

class Image(models.Model):
    def upload_image_to(instance, filename):
        return f'events/{instance.event_id.event_name}/{filename}'
    
    event_id = models.ForeignKey(Event, on_delete=models.CASCADE)
    image_name = models.CharField(max_length=200)
    image = models.ImageField(upload_to=upload_image_to)

    def __str__(self):
        return self.image_name

You can change the filename as well, you can rewrite the upload_image_to function to:

def upload_image_to(instance, filename):
    ext = filename.rsplit('.', 1)[-1]
    return f'events/{instance.event_id.event_name}/{instance.image_name}.{ext}'

Here we thus split right-to-left, and only retain the last part as extension.


Note: Normally one does not add a suffix _id to a ForeignKey field, since Django will automatically add a "twin" field with an _id suffix. Therefore it should be scene, instead of scene_id.

Upvotes: 1

Related Questions