0

I need to show multiple images uploaded in the Admin page (using FileField) in my html.

I'm currently using:

Python 3.6.0b4

Django 1.10.3

I can currently show if the model only has one image but when I try to put multiple images, I have no idea how to show it.

Here is my code:

models.py

class Product(models.Model):
    name = models.CharField(max_length=140)
    created_by = models.ForeignKey(User,null=True)

    def __str__(self):
        return self.name

class ProductImage(models.Model):
    name= models.ForeignKey(Product)
    image = models.FileField(upload_to='media/',null=True,blank=True)

admin.py

class ProductImageInline(admin.TabularInline):
    model = ProductImage

class ProductModelAdmin(admin.ModelAdmin):
    exclude = ('created_by',)

    inlines = [ProductImageInline]

    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
        obj.save()


admin.site.register(Product,ProductModelAdmin)

If I add

image = models.FileField(upload_to='media/',null=True,blank=True)

in my model.py, I can show it in the html like this:

<img width=200 src="{{product.image.url}}" /></a>

How can I show the Multiple Images in the html? I'm fairly new to Django but have experience on web development.

Thanks in advance.

Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
GG WordPress
  • 63
  • 1
  • 16

1 Answers1

0

If you have many-to-one relation you can get all related to the object records using <modelname>_set property.

So try iterate through all images in productimage_set:

{% for image in product.productimage_set.all %}
    <img src="{{image.image.url}}">
{% endfor %}
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • Wow. Thanks a lot. Totally works. Can I ask one last question? How can I show the images uploaded in the Admin Page in the Editing the Model page. It only shows the file path leading to the Image. Thanks. – GG WordPress Dec 07 '16 at 10:11