All Іѕ Vаиітy
All Іѕ Vаиітy

Reputation: 26442

Cloudinary multiple image upload in django?

I have an image upload defined as follows in my Django app with Cloudinary package,

class Photo(models.Model):
    photo = CloudinaryField('image')

I Would like to make this field upload mutliple images. How do I do this?

Upvotes: 4

Views: 841

Answers (2)

Lemayzeur
Lemayzeur

Reputation: 8525

I'd do it like that:

class Photo(models.Model):
    photos = models.ManyToManyField('ChildPhoto',blank=True)

class ChildPhoto(models.Model):
    photo = CloudinaryField('image')

You can upload many photos and the Photo model will have a manytomany to the ChildPhoto model

Upvotes: 3

hoefling
hoefling

Reputation: 66271

A photo holding multiple images becomes a photo album, or a photo gallery. I'd remodel al follows:

class PhotoAlbum(models.Model):
    name = models.CharField()  # or whatever a photo album has

class Photo(models.Model):
    file = CloudinaryField('image')
    album = models.ForeignKey(PhotoAlbum, on_delete=models.CASCADE, related_name='photos')

Usage example:

>>> album = PhotoAlbum.objects.create(name='myalbum')
>>> photo = Photo.objects.create(album=album, image=...)

Now, the Photo knows its PhotoAlbum:

>>> photo = Photo.objects.first()
>>> photo.album
<PhotoAlbum: myalbum>

The PhotoAlbum keeps track of all the Photos:

>>> album = PhotoAlbum.objects.first()
>>> album
<PhotoAlbum: myalbum>
>>> album.photos.all()
<QuerySet [<Photo: Photo-1>]>
>>> album == Photo.objects.first().album
>>> True
>>> Photo.objects.first() == album.photos.first()
>>> True

Upvotes: 6

Related Questions