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 example, just because that's easy. So, imagine I have 2 models like this:
class Book(models.Model):
title = models.CharField(max_length=100)
class BookImage(models.Model):
book = models.ForeignKey(Book)
image = models.ImageField()
is_cover = models.BooleanField()
Now, as you can see a book can have multiple images. I want to rename the uploaded images to [book title]-[image-id].jpg (or whatever image extension there is of course). However, I want image-id to be unique per book. If that makes sense.
So if I have BookA, I want the images to be called BookA-1, BookA-2 and BookA-3 etc. And BookB starts at 1 again, BookB-1, BookB-2, BookB3 etc.
Any idea how I can do this? I've been thinking about it myself, but I can't come up with a really good solution. At first I thought I could do a count on the number of images and add 1 to that, but then you would run into problems if you delete images. I also thought about just keeping track of the ids in a separate Model, but that sounds so overly 'complicated'. And to make things 'worse', I would like to upload multiple images at once (well, the image upload is an inline in the Django admin), so it has to be able to work with that too... So, I was wondering if anyone here has a good idea? Is there even a simple solution?
I've also been googling a bit, but either nobody ever had any problems with this, or I just (well, probably) can't come up with the correct search term (in the same way I couldn't come up with a correct title :P).
Thanks for reading!
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()