[Django]-Django. Several images for product

3πŸ‘

βœ…

What you can use here is Admin inlines that helps you easily edit/updated related items.

class ProductImagesInline(admin.StackedInline):
    model = Images

class ProductAdmin(admin.ModelAdmin):
    list_display = ['name', 'slug', 'category', 'price', 'stock', 'available', 'created', 'updated']
    list_filter = ['available', 'created', 'updated', 'category']
    list_editable = ['price', 'stock', 'available']
    prepopulated_fields = {'slug': ('name',)}
    inlines = [ProductImagesInline]

Once images you can access them like product.images.all()

πŸ‘€Bipul Jain

1πŸ‘

Use one of the Inline Admins for the Image (yes, you should give it a singular name!) model:

class ImageInline(admin.TabularInline):
    model = Image

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

For properly displaying images in templates, you should consider a thumbnail library like sorl or easy-thumbnails:

# sorl example
{% for image in product.images.all %}
    {% thumbnail image.image "500x500" format="PNG" upscale=False as thumb %}
    #                  ^^^^^ you need the image field here
    <img src="{{ thumb.url }}" alt="{{ product.name }}">
    {% endthumbnail %}
{% endfor %}

Beyond that, you can access an Imageβ€˜s url via image.image.url. This is where your original image file will be served. This requires you to have MEDIA_ROOT and MEDIA_URL properly configured.

πŸ‘€user2390182

1πŸ‘

models.py

class Product(models.Model):
    ''''fields''''

class Image(models.Model):
    image = models.ImageField()
    product = models.ForeignKey(Product, default=None, related_name='images',on_delete=models.PROTECT)

admin.py

from yourapp.models import Product, Images

class InlineImage(admin.TabularInline):
    model = Images

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

admin.site.register(Product, ProductAdmin)
πŸ‘€Cadmus

Leave a comment