【问题标题】:Django - ImageField with multiple imagesDjango - 具有多个图像的ImageField
【发布时间】:2022-12-07 00:52:42
【问题描述】:

我有一个具有 ImageField 的模型。我希望用户能够为模型的一个对象上传多张图片——而不仅仅是一张图片。如何才能做到这一点?无论是使用和图像字段还是其他方法。

【问题讨论】:

标签: django django-models


【解决方案1】:

您不能在一个 ImageField 中存储多个图像。

这个问题的一个解决方案是创建一个额外的模型(我将它称为我的社交网络宠物项目的“附件”,称呼你的任何适合你的东西)并让它在外键中引用原始模型。这样你就可以上传任意数量的图像,并为每个新图像创建一个新模型的实例。

示例附件模型:


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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 2019-01-05
    相关资源
    最近更新 更多