Django-admin uploading multiple photos at a time?

Hello. For a project, I need to be able to upload multiple images (different amounts) for each product. A good example is any mail where you can select and upload n-number of photos. Is it possible to do this if then how? django-photologue is not suitable, due to the fact that you must first collect the photo in a zip, and then send it to the current. But I can't choose a few photos myself django version 2.2

Author: GTR, 2019-12-18

2 answers

First create an image model associated with your product:

class Product(Model):
  ...
  description = TextField()  
  ...


class ProductImage(Model):
  image = ImageField(upload_to='product_images/%Y/%m/%d/%H/%M/%S/') # здесь укажите куда сохранять изображения
  product = ForeignKey(Product, related_name="images")

Then, in your admin.py file, you can represent ProductImage as inline

from django.contrib import admin
from models import *


class ProductImageAdmin(admin.ModelAdmin):
  pass


class ProductImageInline(admin.StackedInline):
  model = ProductImage
  max_num = 10
  extra = 0


class ProductAdmin(admin.ModelAdmin):
  inlines = [ProductImageInline,]

admin.site.register(ProductImage, ProductImageAdmin)
admin.site.register(Product, ProductAdmin)

P.S. If you want to flexibly change the image storage path, then use a special function for this:

def product_image_directory_path(instance, filename):
    # instance - экземпляр модели ProductImage
    # filename - имя сохраняемого файла
    # Изображение будет сохранено в MEDIA_ROOT/product_<id>/<filename>
    return 'product_{0}/{1}'.format(instance.product.id, filename)

And then pass this function to the value upload_to in ImageField:

  ...
  image = ImageField(upload_to=product_image_directory_path)
  ...
 1
Author: Narnik Gamarnik, 2019-12-18 21:35:31