GaripTipici
GaripTipici

Reputation: 508

Changing name of image uploaded

I'm a noob django developer, I can upload images but name of the images have to be changed to image ID or whatever I want.

In addition to this, when I delete entries, images are still resting in the media file but I don't want this.

What I have to add ?

Here is my models.py

from django.db import models

class Flower(models.Model):
    name = models.CharField(max_length = 30)
    price = models.IntegerField()
    image = models.ImageField(upload_to = 'static/media')
    def __unicode__(self):
        return self.name

Upvotes: 0

Views: 353

Answers (1)

Derek Kwok
Derek Kwok

Reputation: 13058

To customize the path and filename of where the files are stored, you'll need to define a method for upload_to. Here's an example:

def my_upload_to(instance, filename):
    # "instance" is an instance of Flower
    # return a path here
    return 'my/path/to/storage/' + filename

class Flower(models.Model):
    image = models.ImageField(upload_to=my_upload_to)

See https://docs.djangoproject.com/en/dev/ref/models/fields/#filefield

To delete the underlying file, you'll need to make a call manually:

flower = Flower.objects.get(id=1)
flower.image.delete()

You can choose to override your model's delete() method, or use signals pre_delete or post_delete to delete the associated files automatically.

See https://docs.djangoproject.com/en/dev/ref/models/fields/#filefield-and-fieldfile

Upvotes: 2

Related Questions