Django -包含多个图像的ImageField



我有一个具有ImageField的模型。我希望用户能够上传模型对象的多个图像-而不仅仅是单个图像。如何做到这一点?

不能在一个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'

您可以将多个图像存储到您的django产品模型中的单个字段中。

总结的逻辑是创建一个模型表单字段,支持多文件上传选择,然后上传这些图像(在我的例子中,我将它们上传到cloudinary,因为我已经设置了cloudinary来处理我在django项目中的所有文件上传),然后检索这些图像的url并将它们分配给模型实例中的单个字段,这样你就可以随时获取该字段并获得图像的url。

下面是我当前实现的代码片段,以帮助您假设我有一个Product,Model

class Product(models.Model):
#your other fields
multiview_images = models.TextField(blank=True,null=True) 
#other fields
def get_multiview_images_list(self):
if self.multiview_images:
try:
urls = json.loads(self.multiview_images)
return [ {url} for url in urls]
except json.JSONDecodeError as e:
print("JSON Decode Error:", e)
return []
def set_multiview_images(self, images):
self.multiview_images = json.dumps(images)

<标题>productmodelform.py h1> admin.py h1> modelform字段将创建一个多上传按钮,使您能够从本地存储上传多个文件,然后它将上传它们到cloudary,并将每个图像url作为列表返回到产品模型中的图像字段,该产品模型将作为列表或url数组存储在您的图像字段中。

当您对产品端点进行api调用时,get_multiview_images_list字段看起来像这样(不要忘记在您的serializers.py字段列表中添加以公开该字段)

[
[url1],
[url2],
[url3],
[url10]
]

请注意,这个实现只在你从django admin仪表板上传的时候起作用。您始终可以在productmodelform中设置上传的最大和最小数量的限制。

最新更新