Md Morshed Alam
Md Morshed Alam

Reputation: 97

How to show multiple images from models through loop in django templete

I am trying to create a page where I can show product details with an image from my data models using a loop in Django model, but when I go item list it's work for details except image, in image section, it shows alt text. please help me.

my models:

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name


class Item(models.Model):
    name = models.CharField(max_length=150)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    is_active = models.BooleanField(default=True)
    model_pic = models.ImageField(upload_to = 'static/media/')

    def __str__(self):
        return self.name

my views:

def item_list(request, category_id):
    category_name = Category.objects.get(pk=category_id)
    list_items = Item.objects.filter(category=category_name)
    context = {
       'list_items': list_items,
    }
    return render(request, 'inventory/item_list.html', context)

my templete:

{% for item in list_items %}
       <tr>
           <td>{{ forloop.counter }}</td>
           <td>{{ item.name }}</td>
           <td>{{ item.category }}</td>
           <td>{{ item.is_active }}</td>
           <td><a href="{% url 'item_delete' item.pk %}">Delete</a></td>
           <td><img src="{{ item.model_pic.url }}" alt="Photo"></td>
        </tr>
 {% endfor %}

output:enter image description here

Upvotes: 1

Views: 1302

Answers (2)

Ansif_Muhammed
Ansif_Muhammed

Reputation: 436

def item_list(request, category_id):
    category_name = Category.objects.get(pk=category_id)
    list_items = Item.objects.filter(category=category_name)
    context = {
       'list_items': list_items,
    }
    return render(request, 'inventory/item_list.html', context)

here the context dictionary will be apssed to the corresponding url item_list.html

in settings you have to decalre your static parameters, once done; In item_list.html. you have to use {% static %} and then loop through your context elements. in

 <img src="{% static variable %}" %}>

Upvotes: 0

Aaron Hampton
Aaron Hampton

Reputation: 894

If this is happening during development, make sure your application is configured to serve media. Update your url configuration. For example:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

For more info, see:

https://docs.djangoproject.com/en/2.1/howto/static-files/#serving-files-uploaded-by-a-user-during-development

If that is already configured, check the source of your file to see what is being displayed. "Photo" is showing because the web browser cannot locate the image.

Upvotes: 2

Related Questions