how to get image url attribute in django

4k Views Asked by At

i have a problem with getting image url in django template. In views file i am getting "product__stock_keeping_unit__image" which is related products' image as below.

data = models.Product.objects.filter(category__slug=slug, product__is_default=True).values("id", "name", "product__sku", "slug", "category__name", "product__store_price", "product__sub_product__units", "product__stock_keeping_unit__image")

in template file i am trying to display image

{% for item in data %}
        <div class="col-lg-3 mb-4 text-center">
            <div class="product-entry border">
                <a href="#" class="prod-img">
                    <img src="{{ item.product__stock_keeping_unit__image.url }}">
                </a>
                <div class="desc">
                    <h2><a href="{% url 'product_detail' item.slug item.product__sku %}">{{ item.name }}</a></h2>
                    <span class="price">${{ item.product__store_price }}</span>
                </div>
            </div>
        </div>
       {% endfor %}

Everything works fine except img field. In the page source i am getting empty string. But when i write <img src="{{ item.product__stock_keeping_unit__image }}"> i am getting image path in page source images/men-shoes.jpg but not add MEDIA_URL /media/images/men-shoes.jpg into path.

Settings.py

MEDIA_ROOT =  os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

How can i solve this problem. Thank in advance!

2

There are 2 best solutions below

0
JSRB On BEST ANSWER

You have to add the media prefix like so:

src="{% get_media_prefix %}{{ item.product__stock_keeping_unit__image }}">

and set some url settings for development mode like so:

# urls.py

..
urlpatterns = [
   ...
]

# Serving the media files in development mode
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
    urlpatterns += staticfiles_urlpatterns()
1
Krishna Sunuwar On

.values(...) returns queryset containing dictionary, see here. Therefore you will not able to access url property of image field.

Use standard django object that exposes property of the image field. You can use following:

Query:

data = models.Product.objects.filter(category__slug=slug, product__is_default=True)

In template

<img src="{{ item.product.tock_keeping_unit.image.url }}">

p.s. you can use select_related for performance