Skip to content Skip to sidebar Skip to footer

Django, How To Rename Images Using A New Auto-numbering Per Foreign Key?

Ok, that title is probably as vague as vague things can get, but I couldn't come up with something good. Let me explain my problem. For the explanation, I'll use books as an exampl

Solution 1:

firs you define a function to handle the upload image and pass this to your imagefield.

def book_image_upload(instance, filename):
        book_title = instance.book.title
        instance_id = instance.id
        extension = filename.split(".")[-1]
        new_filename = "%s-%s.%s" %(book_title, instance_id,extension)
        new_filepath = "books/%s" %(new_filename)
        return new_filepath

class BookImage(models.Model):
    book = models.ForeignKey(Book)
    image = models.ImageField(upload_to=book_image_upload)
    is_cover = models.BooleanField()

Post a Comment for "Django, How To Rename Images Using A New Auto-numbering Per Foreign Key?"