Home > OS >  Django - ImageField with multiple images
Django - ImageField with multiple images

Time:12-07

I have a model that has an ImageField. I want users to be able to upload multiple images for an object of the model - not only a single image. How can this be done? Whether with and image field or another approach.

CodePudding user response:

You cannot store several images in one ImageField.

One solution for this problem would be to create an additional model (I called it "Attachment" for my social network pet project, call your's whatever should suit you) and have it reference the original model in a Foreign key. That way you can upload as many images as you want and create an instance of that new model for each new image.

Example Attachment model:


class Attachment(DatetimeCreatedMixin, AuthorMixin):
    class AttachmentType(models.TextChoices):
        PHOTO = "Photo", _("Photo")
        VIDEO = "Video", _("Video")

    file = models.ImageField('Attachment', upload_to='attachments/')
    file_type = models.CharField('File type', choices=AttachmentType.choices, max_length=10)

    publication = models.ForeignKey(TheOriginalModelYouUsedImageFieldIn, on_delete=models.CASCADE, verbose_name='Model that uses the image field')

    class Meta:
        verbose_name = 'Attachment'
        verbose_name_plural = 'Attachments'
  • Related