Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django change name of image from ImageField

I would like to change the name of an image coming renaming it to the color of the door.

Here is my code:

class Door(models.Model) :
    image = models.ImageField(upload_to='doors')
    color = models.ForeignKey(Color, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=10, decimal_places=2, default='119.99')

I've looked at multiple things but I don't know yet how to do it.
Please help me if you know the answer to my problem.

like image 750
Fantasmo Clone27 Avatar asked Sep 06 '25 03:09

Fantasmo Clone27


1 Answers

You can do like this:

def upload_location(instance, filename):
    filebase, extension = filename.split('.')
    return 'images/%s.%s' % (instance.color.name, extension)

class Color(models.Model):
    name = models.CharField(max_length=20)


class Door(models.Model) :
    image = models.ImageField(upload_to=upload_location)
    color = models.ForeignKey(Color, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=10, decimal_places=2, default='119.99')
like image 199
Mohammad Ali Avatar answered Sep 07 '25 20:09

Mohammad Ali